如何与条件一起使用Apply函数?

时间:2020-06-22 18:30:00

标签: python pandas lambda apply

我正在使用的数据框有一个名为“性别”的列,其中填充有“男性” /“女性”。 我需要将“ male” /“ female”更改为数字,即0或1。

我正在尝试以下代码

result =  df.apply(lambda x: 1 if x == 'male' else 0, )

错误是

AttributeError: 'str' object has no attribute 'Sex'

2 个答案:

答案 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