pandas -替换列值 [英] Pandas - replacing column values
问题描述
我知道这个问题有很多主题,但是没有一种方法适合我,所以我要发布有关我的具体情况的信息
I know there are a number of topics on this question, but none of the methods worked for me so I'm posting about my specific situation
我有一个看起来像这样的数据框:
I have a dataframe that looks like this:
data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
data['sex'].replace(0, 'Female')
data['sex'].replace(1, 'Male')
data
我想做的是将性别列中的全0替换为女性",将所有1替换为男性",但是当我使用上面的代码时,数据框中的值似乎没有改变
What I want to do is replace all 0's in the sex column with 'Female', and all 1's with 'Male', but the values within the dataframe don't seem to change when I use the code above
我错误地使用了replace()吗?还是有更好的方法可以有条件地替换值?
Am I using replace() incorrectly? Or is there a better way to do conditional replacement of values?
推荐答案
Yes, you are using it incorrectly, Series.replace()
is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace
keyword argument as True
Example -
data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)
此外,您还可以通过对to_replace
参数和value
参数使用list
将以上内容组合为单个replace
函数调用,示例-
Also, you can combine the above into a single replace
function call by using list
for both to_replace
argument as well as value
argument , Example -
data['sex'].replace([0,1],['Female','Male'],inplace=True)
示例/演示-
In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)
In [12]: data
Out[12]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
您还可以使用字典,例如-
You can also use a dictionary, Example -
In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])
In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)
In [17]: data
Out[17]:
sex split
0 Male 0
1 Female 1
2 Male 0
3 Female 1
这篇关于 pandas -替换列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!