This question already has answers here:
Pandas conditional creation of a series/dataframe column
                                
                                    (8个答案)
                                
                        
                                2年前关闭。
            
                    
我想基于熊猫中其他列填充缺失值。
这是我的桌子:

Gender     Married
Male       Yes
Male       Yes
Female     No
Female     No
Male       NaN
Female     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)


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

最佳答案

我相信仅在过滤的行中需要mapdictionary

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


映射fillnaSeries的另一种解决方案:

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

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

10-12 17:25