我想根据熊猫中的其他列填充缺失值。这是我的表:Gender MarriedMale YesMale YesFemale NoFemale NoMale NaNFemale NaN如果性别为男性,我将填充已婚字段的缺失值 -> 已婚为是,否则已婚为否:df['Married'].fillna(df[df['Married'].isnull()].apply(lambda x: 'Yes' if (df[df['Married'].isnull()]['Gender'] is 'Male') else 'No', axis=1), inplace=True)但它失败了,我尝试了很多方法,但没有得到预期的结果。我希望收到你们所有人。
1 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
我相信你需要map有dictionary只在过滤行:
mask = df['Married'].isnull()
df.loc[mask, 'Married'] = df.loc[mask, 'Gender'].map({'Male':'Yes', 'Female':'No'})
print (df)
Gender Married
0 Male Yes
1 Male Yes
2 Female No
3 Female No
4 Male Yes
5 Female No
另一个解决方案numpy.where:
mask = df['Married'].isnull()
df.loc[mask, 'Married'] = np.where(df.loc[mask, 'Gender'] == 'Male', 'Yes','No')
print (df)
Gender Married
0 Male Yes
1 Male Yes
2 Female No
3 Female No
4 Male Yes
5 Female No
fillna映射的另一个解决方案Series:
df['Married'] = df['Married'].fillna(df['Gender'].map({'Male':'Yes', 'Female':'No'}))
添加回答
举报
0/150
提交
取消