Python中用for循环按条件替换Partner_salary列空值的代码求助
Solution to Fill Missing Partner_salary Values
Step 1: Calculate the Median Salary for Working Partners
First, compute the median of Partner_salary where Partner_working is 'Yes', excluding missing values:
import pandas as pd # Assuming df is your pre-loaded DataFrame median_working_salary = df[df['Partner_working'] == 'Yes']['Partner_salary'].median()
Step 2: Loop Through Rows to Fill Missing Values
Use a for loop with if-else logic to replace each missing value based on the Partner_working status:
for idx in df.index: # Check if Partner_salary has a missing value if pd.isna(df.loc[idx, 'Partner_salary']): # Fill with pre-calculated median if partner is working if df.loc[idx, 'Partner_working'] == 'Yes': df.loc[idx, 'Partner_salary'] = median_working_salary # Fill with 0 if partner is not working else: df.loc[idx, 'Partner_salary'] = 0
Key Notes
- This code strictly follows your requirement of using a
forloop paired withif-elseconditions. - For better performance on larger datasets, vectorized operations (e.g., boolean masking with
df.loc) are recommended, but this implementation aligns with your specified method.
内容的提问来源于stack exchange,提问作者Neha
相关产品推荐
相关产品推荐

