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

Python Pandas:分组内累计利润列标准化问题求助

Pandas分组累计利润标准化解决方案

你的问题核心是分组最大值无法和原数据行正确对齐:直接调用groupby('Sub-Category')['Cumulative Profit'].max()返回的是每个分类对应单个最大值的Series,和原DataFrame的整数索引无法匹配,导致除法运算结果错误。

无需lambda函数的原生解决方案是使用transform('max'),它会将分组最大值广播到该分组的每一行,实现行对齐:

us_discount = us.groupby(['Sub-Category', 'Discount'], as_index = False)['Profit'].sum()
us_discount['Cumulative Profit'] = us_discount.groupby('Sub-Category')['Profit'].cumsum()

# 计算分组内累计利润最大值并广播到每行
group_max = us_discount.groupby('Sub-Category')['Cumulative Profit'].transform('max')
# 生成标准化列
us_discount['Normalized Cumulative Profit'] = us_discount['Cumulative Profit'] / group_max

us_discount.head()

原理说明

transform('max')会对每个Sub-Category分组计算Cumulative Profit的最大值,然后将该值复制到分组内的所有行,生成一个和原DataFrame行数一致的Series。这样就能和Cumulative Profit列逐行对应完成除法,得到每个分组内的标准化累计利润值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:35:00