我试图替换一个数据框架的一列的值。列('female')只包含值'female'和'male'。

我尝试过以下方法:

w['female']['female']='1'
w['female']['male']='0' 

但收到的是与之前结果完全相同的副本。

理想情况下,我希望得到类似于以下循环元素的输出。

if w['female'] =='female':
    w['female'] = '1';
else:
    w['female'] = '0';

我已经查看了gotchas文档(http://pandas.pydata.org/pandas-docs/stable/gotchas.html),但不明白为什么什么都没有发生。

任何帮助都将不胜感激。


当前回答

dic = {'female':1, 'male':0}
w['female'] = w['female'].replace(dic)

.replace有一个字典作为参数,在这个字典中你可以做任何你想要或需要的事情。

其他回答

这非常紧凑:

w['female'][w['female'] == 'female']=1
w['female'][w['female'] == 'male']=0

另一个好例子:

w['female'] = w['female'].replace(regex='female', value=1)
w['female'] = w['female'].replace(regex='male', value=0)
w.female = np.where(w.female=='female', 1, 0)

如果有人在寻找一个麻木的解决方案。这对于基于条件替换值非常有用。if和else条件都是np.where()中固有的。使用df.replace()的解决方案可能是不可行的,如果列包含除'male'之外的许多唯一值,所有这些值都应该替换为0。

另一种解决方案是连续使用df.where()和df.mask()。这是因为它们都没有实现else条件。

w.female.where(w.female=='female', 0, inplace=True) # replace where condition is False
w.female.mask(w.female=='female', 1, inplace=True) # replace where condition is True

你也可以使用apply和。get i.e.。

"菲玛"等于"菲玛"克里奥耳语(——“画”:0,可说是家常便饭”:1,.get):

w = pd.DataFrame({'female':['female','male','female']})
print(w)

Dataframe w:

   female
0  female
1    male
2  female

使用apply替换字典中的值:

w['female'] = w['female'].apply({'male':0, 'female':1}.get)
print(w)

结果:

   female
0       1
1       0
2       1 

注意:如果数据帧中所有可能的列的值都是在字典else中定义的,那么apply with dictionary应该被使用,对于那些没有在字典中定义的列,它将为空。

使用系列。使用Series.fillna映射

如果您的列包含的字符串多于female和male,则Series。map在这种情况下将失败,因为它将为其他值返回NaN。

这就是为什么我们要用fillna来连接它

.map失败的例子:

df = pd.DataFrame({'female':['male', 'female', 'female', 'male', 'other', 'other']})

   female
0    male
1  female
2  female
3    male
4   other
5   other
df['female'].map({'female': '1', 'male': '0'})

0      0
1      1
2      1
3      0
4    NaN
5    NaN
Name: female, dtype: object

对于正确的方法,我们使用fillna进行链映射,所以我们用原始列的值填充NaN:

df['female'].map({'female': '1', 'male': '0'}).fillna(df['female'])

0        0
1        1
2        1
3        0
4    other
5    other
Name: female, dtype: object
w.female.replace(to_replace=dict(female=1, male=0), inplace=True)

参见pandas.DataFrame.replace()文档。