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

任何帮助都将不胜感激。


当前回答

如果我没理解错的话,你想要这样的东西:

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

(这里我将值转换为数字,而不是包含数字的字符串。你可以把它们转换成“1”和“0”,如果你真的想,但我不知道为什么你想这样做。)

你的代码不能工作的原因是因为在列上使用['female'] (w['female']['female']中的第二个'female')并不意味着“选择值为'female'的行”。这意味着选择索引为“female”的行,而这些行在你的DataFrame中可能没有。

其他回答

我认为,在答案应该指出哪种类型的对象,你得到的所有方法上面建议:它是系列或数据帧。

当你看到w。female的专栏。或者w[[2]](其中,假设2是你的列的数字),你会得到DataFrame。 在这种情况下,你可以使用DataFrame方法,比如。replace。

当你使用。loc或iloc时,你会返回Series,而Series没有。replace方法,所以你应该使用apply, map等方法。

w.female.replace(to_replace=dict(female=1, male=0), inplace=True)

参见pandas.DataFrame.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
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

这也可以工作:

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