我正在使用的数据框有一个名为“性别”的列,其中填充有“男性” /“女性”。 我需要将“ male” /“ female”更改为数字,即0或1。
我正在尝试以下代码
result = df.apply(lambda x: 1 if x == 'male' else 0, )
错误是
AttributeError: 'str' object has no attribute 'Sex'
答案 0 :(得分:1)
label_dict = {'male':0, 'female':1}
df['Sex'] = df.category.replace(label_dict)
您可以使用字典将dataframe列中的值映射到字典中的相应值。
答案 1 :(得分:0)
使用.replace
df['Sex'] = df['Sex'].replace({'male': 1, 'female': 0})
使用.map
df['Sex'] = df['Sex'].map({'male': 1, 'female': 0})
使用布尔类型转换的版本
df['Sex'] = (df['Sex'] == 'male').astype(int)
最后一个版本的优点是使所有与男性不同的值都为0