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

如何对DataFrame按attribute分组,排除desc_type1/2行并计算折扣总和

解决方案

核心思路

先拆分数据集为有效属性行(排除desc_type1/desc_type2)和折扣行,通过ID关联两者,再按attribute分组计算所需指标:

代码实现

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]
})

# 1. 分离有效属性行与折扣行
valid_attr = df[~df['attribute'].isin(['desc_type1', 'desc_type2'])]
discount_records = df[df['attribute'].isin(['desc_type1', 'desc_type2'])]

# 2. 按ID聚合每个ID的总折扣
id_total_discount = discount_records.groupby('ID')['discount'].sum().reset_index(name='total_discount')

# 3. 关联有效属性行与ID折扣数据,无折扣的ID填充0
merged_data = valid_attr.merge(id_total_discount, on='ID', how='left').fillna({'total_discount': 0})

# 4. 按attribute分组计算最终指标
final_result = merged_data.groupby('attribute').agg(
    ID_count=('ID', 'nunique'),
    value_sum=('value', 'sum'),
    discount_sum=('total_discount', 'sum')
).reset_index()

print(final_result)

输出结果

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

逻辑说明

  • 用isin精准筛选需要保留/排除的行,确保有效属性行仅包含真实业务属性
  • 按ID聚合折扣,保证同一ID下的所有折扣项被求和合并
  • left merge确保无折扣数据的ID(如示例中的ID=20)不被丢弃,缺失值填充0保证统计准确性
  • 分组时用nunique统计不同ID数量,sum分别计算value总和与折扣总和

内容的提问来源于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 14:54:19