我试图替换一个数据框架的一列的值。列('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'] = w['female'].map({'female': 1, 'male': 0})

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

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

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

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

pandas中还有一个叫做factorize的函数,您可以使用它自动完成这类工作。它将标签转换为数字:['male', 'female', 'male'] ->[0,1,0]。更多信息请看这个答案。

你可以使用loc编辑一个数据帧的子集:

df.loc[<row selection>, <column selection>]

在这种情况下:

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

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