我查过这个问题,大多数问题都是针对更复杂的替换。但是,就我而言,我有一个非常简单的数据框作为测试假人。
目的是用 nan 替换数据框中任意位置的字符串,但这似乎不起作用(即不替换;没有任何错误)。我试过用另一个字符串替换,但它也不起作用。例如
d = {'color' : pd.Series(['white', 'blue', 'orange']),
'second_color': pd.Series(['white', 'black', 'blue']),
'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan)
输出仍然是:
color second_color value
0 white white 1
1 blue black 2
2 orange blue 3
这个问题通常使用 inplace=True
来解决,但也有一些注意事项。另请参阅 Understanding inplace=True in pandas .
最佳答案
鉴于这是搜索“Pandas replace is not working”时谷歌的最高结果,我还想提一下:
replace does full replacement searches, unless you turn on the regex switch. Use regex=True, and it should perform partial replacements as well.
我花了 30 分钟才找到答案,所以希望我已经为下一个人节省了 30 分钟。
关于python - replace() 方法不适用于 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593550/