You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 for loop paired with if-else conditions.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:45:41