首页 > 解决方案 > 替换列中的值会清空列

问题描述

我的数据框中有一列prix名为features. 该列应该具有三个值:(1, 2, 3). 我的价值4是噪音。我想43. 我这样做了:

# initially string and convert to int
features.prix.astype(int)
# code to replace
features['prix'] = features['prix'].replace('4', '3', inplace=True)

但是在我运行这个之后,features['prix']变得空了。当我print(features),我已经None在列Prix

如果我做错了什么,请告诉我。

谢谢

标签: pythondataframereplace

解决方案


当您inplace = True在 pandas 中使用参数时,该函数会覆盖您的原始 DataFrame 并且不返回任何内容(即返回 None),因此,由于您将此结果分配给您的featrues['prix']列,它会被 None 覆盖。

您应该选择是使用 inplace 还是将 result 分配给您的列,即:

要么做

features['prix'].replace('4','3',inplace=True)

或者

features['prix'] = features['prix'].replace('4','3')

请注意,inplace现在不鼓励使用参数,因为他们计划最终弃用它,因此现在首选第二种方法。


推荐阅读