如何基于其他列条件使用fillna()填充Credit_History缺失值
Solution for Filling Missing
Credit_History Values Got it, let's tackle this missing value filling task step by step. I’ll assume you’re working with a pandas DataFrame named df (swap this with your actual DataFrame name if needed). Here’s how to implement each of your specified scenarios using conditional logic combined with direct value assignment:
Scenario 1: Fill with 0 when Self_Employed = 'Y' and Married = 'N'
We’ll target rows where Credit_History is NaN and the two conditions are satisfied:
# Locate matching rows and fill Credit_History with 0 df.loc[(df['Credit_History'].isna()) & (df['Self_Employed'] == 'Y') & (df['Married'] == 'N'), 'Credit_History'] = 0
Scenario 2: Fill with 1 when Self_Employed = 'N' and ApplicantIncome > 20000
Next, handle the second set of conditions for any remaining NaN values:
# Locate rows meeting the criteria and fill with 1 df.loc[(df['Credit_History'].isna()) & (df['Self_Employed'] == 'N') & (df['ApplicantIncome'] > 20000), 'Credit_History'] = 1
Scenario 3 (Partial): Handle Self_Employed = 'Y', Married = 'N' and ApplicantIncome > 2000
It looks like this scenario was cut off, but let’s use a placeholder example (replace [your_target_value] with the actual value you want to fill):
# Insert your desired fill value in place of [your_target_value] df.loc[(df['Credit_History'].isna()) & (df['Self_Employed'] == 'Y') & (df['Married'] == 'N') & (df['ApplicantIncome'] > 2000), 'Credit_History'] = [your_target_value]
Quick Notes:
- Run these operations sequentially if there’s any chance of overlapping conditions (though your scenarios seem mutually exclusive, this ensures no overwriting of already filled values).
- If you still have leftover NaN values after applying these rules, you can fall back to the statistical insights you already calculated—like filling with the overall median of
Credit_Historyor using other column-specific patterns you identified.
内容的提问来源于stack exchange,提问作者uharsha33
相关产品推荐
相关产品推荐

