我试图替换一个数据框架的一列的值。列('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中可能没有。

其他回答

你也可以使用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

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

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
dic = {'female':1, 'male':0}
w['female'] = w['female'].replace(dic)

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

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

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