我试图替换一个数据框架的一列的值。列('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),但不明白为什么什么都没有发生。

任何帮助都将不胜感激。


当前回答

使用系列。使用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(['male', 'female'], [1, 0], inplace=True)
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
dic = {'female':1, 'male':0}
w['female'] = w['female'].replace(dic)

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

如果你只有两个类,你可以使用相等运算符。例如:

df = pd.DataFrame({'col1':['a', 'a', 'a', 'b']})

df['col1'].eq('a').astype(int)
# (df['col1'] == 'a').astype(int)

输出:

0    1
1    1
2    1
3    0
Name: col1, dtype: int64

使用系列。使用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