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

如何基于多分组列用均值替换Pandas DataFrame中的零值

Fixing the 0 Value Replacement in Current Loan Amount Column

Your code was on the right track, but the issue is that you're applying the transformation to the entire grouped DataFrame instead of just the Current Loan Amount column. That's why you're losing other columns and not seeing the changes reflected properly in your original data.

Here's the corrected approach that targets only the column we need to modify, while preserving all other columns:

import pandas as pd

# Assuming your original DataFrame is named data_loan
data_loan['Current Loan Amount'] = data_loan.groupby(['Year', 'Month'])['Current Loan Amount'].transform(
    lambda group: group.replace(0, group[group != 0].mean())
)

How this works:

  • We specifically select the Current Loan Amount column before applying groupby and transform. This ensures we only modify this column, leaving DateTime, Day, Month, and Year untouched.
  • The lambda function operates on each Year-Month group individually:
    1. It filters out 0 values to calculate the mean of valid loan amounts in the group
    2. It replaces any 0 entries in the group with this calculated mean
  • The transform method aligns the modified values back to the original DataFrame's index, so we can directly assign the results to the original column without disrupting other data.

Let's verify with your sample data:

For the Jan-92 group, the non-zero values have a mean of ~302,817. The two rows with 0 (indices 18 and 19) will now be replaced with this mean, while all other columns stay exactly as they were.

If you want to double-check the group means before applying the replacement, you can run:

print(data_loan[data_loan['Current Loan Amount'] != 0].groupby(['Year', 'Month'])['Current Loan Amount'].mean())

内容的提问来源于stack exchange,提问作者saint

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:33:18