首页 > 解决方案 > 使用否定与熊猫替换

问题描述

我有兴趣使用 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

标签: python-3.xpandasreplace

解决方案


如果使用 .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

推荐阅读