我对使用pandas dataframe.replace()感兴趣,但带有否定。我在支持此操作的文档中没有看到任何内容,因此有更好的方法吗?
示例数据框
Color Shape
blue star
red triangle
purple square
代码替换所有不以梯形开头的实例
dataframe['Shape'] = dataframe['Shape'].replace(~['star'], 'trapezoid')
预期数据框
Color Shape
blue star
red trapezoid
purple trapezoid
答案 0 :(得分:2)
如果不需要使用.replace,那么这行得通
df
Color Shape
0 blue star
1 red triangle
2 purple square
df.Shape[df.Shape != "star"] = "trapezoid"
df
Color Shape
0 blue star
1 red trapezoid
2 purple trapezoid
答案 1 :(得分:2)
一种可能的解决方案是:
dataframe.loc[~dataframe['Shape'].str.contains(['star']),'Shape']= 'trapezoid'
如果要提高代码性能,可以使用:
dataframe.loc[~dataframe['Shape']=='star','Shape']= 'trapezoid'
答案 2 :(得分:2)
将regex
与negative lookahead
一起使用会像这样:
df['Shape'] = df.Shape.str.replace('(^((?!star).)*$)', 'trapezoid')
print(df)
Color Shape
0 blue star
1 red trapezoid
2 purple trapezoid