本文介绍了replace() 方法不适用于 Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我查过这个问题,大多数问题都是针对更复杂的替换.但是,就我而言,我有一个非常简单的数据框作为测试虚拟对象.
I have looked up this issue and most questions are for more complex replacements. However in my case I have a very simple dataframe as a test dummy.
目的是用 nan 替换数据帧中任何位置的字符串,但这似乎不起作用(即不替换;没有任何错误).我试过用另一个字符串替换,它也不起作用.例如
The aim is to replace a string anywhere in the dataframe with an nan, however this does not seem to work (i.e. does not replace; no errors whatsoever). I've tried replacing with another string and it does not work either. E.g.
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
推荐答案
您需要重新分配
df = df.replace('white', np.nan)
或传递参数 inplace=True
:
In [50]:
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, inplace=True)
df
Out[50]:
color second_color value
0 NaN NaN 1.0
1 blue black 2.0
2 orange blue 3.0
大多数 Pandas 操作返回一个副本,大多数都有参数 inplace
通常默认为 False
Most pandas ops return a copy and most have param inplace
which is usually defaulted to False
这篇关于replace() 方法不适用于 Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!