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

Pandas分组聚合:排除指定attribute行并汇总对应ID折扣

解决方案

步骤1:拆分并预处理数据

首先把原始数据拆分为主属性行(排除desc_type1和desc_type2)和折扣汇总行(按ID汇总所有desc类型的折扣):

import pandas as pd

# 示例数据
df = pd.DataFrame({
    'ID':[10,10,10,20,30,30],
    'attribute':['attrib_1','desc_type1','desc_type2','attrib_1','attrib_2','desc_type1'],
    'value':[100,0,0,100,30,0],
    'discount':[0,6,2,0,0,13.3]
})

# 提取主属性行(排除desc类型)
main_df = df[~df['attribute'].isin(['desc_type1', 'desc_type2'])].copy()

# 按ID汇总所有desc类型的折扣
discount_total = df[df['attribute'].isin(['desc_type1', 'desc_type2'])].groupby('ID')['discount'].sum().reset_index(name='total_discount')

步骤2:合并主数据与折扣汇总

将主数据和对应ID的总折扣合并,没有折扣的ID自动填充为0:

# 合并数据,无折扣的ID填充0
merged_df = main_df.merge(discount_total, on='ID', how='left').fillna({'total_discount': 0})

步骤3:按attribute分组聚合

最后按attribute分组,统计所需指标:

# 分组聚合得到目标结果
result = merged_df.groupby('attribute').agg(
    ID_count=('ID', 'count'),
    value_sum=('value', 'sum'),
    discount_sum=('total_discount', 'sum')
).reset_index()

print(result)

执行后输出结果:

attribute  ID_count  value_sum  discount_sum
0   attrib_1         2        200           8.0
1   attrib_2         1         30          13.3

关键说明

  • 拆分再合并的逻辑,确保每个主属性行能关联到对应ID的所有desc类型折扣总和
  • 用fillna(0)处理无折扣的ID,避免聚合时出现缺失值
  • 分组聚合时直接使用合并后的total_discount求和,正好满足同一ID下折扣汇总到对应attribute的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:31:06