gpt4 book ai didi

python - 根据其他列 pandas 填充缺失值

转载 作者:行者123 更新时间:2023-12-01 08:54:46 24 4
gpt4 key购买 nike

我想根据 pandas 中的其他列填充缺失值。这是我的表格:

Gender     Married
Male Yes
Male Yes
Female No
Female No
Male NaN
Female NaN

如果性别是男性,我将填写“已婚”字段的缺失值 ->“已婚”为"is",否则“已婚”为“否”:

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)

但是失败了,我尝试了很多方法,但没有得到我期望的结果。希望收到大家的来信。

最佳答案

我相信你需要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映射的系列:

df['Married'] = df['Married'].fillna(df['Gender'].map({'Male':'Yes', 'Female':'No'}))

关于python - 根据其他列 pandas 填充缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com