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

Pandas分组后如何正确处理重复行业数据的聚合计算?

Pandas分组聚合优化方案

需求说明

  • 按IndustrySegmentName分组后,对品牌类字段(BrandRevenueTY、BrandSupplyTY、BrandDemandTY)执行求和操作
  • 对行业类字段(IndustryRevenueTY、IndustrySupplyTY、IndustryDemandTY),因同分组内各酒店数据重复,需选择两种处理方式之一:
    1. 直接取分组内任意一行的字段值(因重复,所有行值一致)
    2. 将原求和结果除以分组内唯一酒店的数量

原实现方式

原代码通过两次groupby分别完成聚合和统计酒店数,逻辑分散:

# 第一次分组:对所有指定字段求和
df_revPAR = df.groupby('IndustrySegmentName', as_index=False)[
    ['BrandRevenueTY', 'BrandSupplyTY', 'BrandDemandTY', 
     'IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']].sum()

# 第二次分组:统计每组唯一酒店数并合并
df_brandcount = df.groupby('IndustrySegmentName', as_index=False)[
    ['Hotel Name']].nunique()
df_revPAR['BrandCount'] = df_brandcount['Hotel Name']

优化方案:单次分组完成所有操作

利用groupby.agg()方法,一次性定义不同字段的聚合规则,避免重复分组,提升效率与可读性。

方案1:行业类字段取分组内单一值(推荐,因重复值无需求和)

# 定义各字段的聚合规则
agg_config = {
    # 品牌类字段求和
    'BrandRevenueTY': 'sum',
    'BrandSupplyTY': 'sum',
    'BrandDemandTY': 'sum',
    # 行业类字段取分组内第一个值(同分组内值重复,任意值均可)
    'IndustryRevenueTY': 'first',
    'IndustrySupplyTY': 'first',
    'IndustryDemandTY': 'first',
    # 统计分组内唯一酒店数量
    'Hotel Name': 'nunique'
}

# 单次分组完成所有聚合
df_revPAR = df.groupby('IndustrySegmentName', as_index=False).agg(agg_config)

# 重命名酒店数字段(可选,提升可读性)
df_revPAR.rename(columns={'Hotel Name': 'BrandCount'}, inplace=True)

方案2:行业类字段用求和结果除以酒店数

若需基于原求和值修正,可在单次分组中同时计算求和值与酒店数,再完成除法:

# 单次分组计算所有必要值
temp_df = df.groupby('IndustrySegmentName', as_index=False).agg(
    # 品牌类字段求和
    BrandRevenueTY=('BrandRevenueTY', 'sum'),
    BrandSupplyTY=('BrandSupplyTY', 'sum'),
    BrandDemandTY=('BrandDemandTY', 'sum'),
    # 行业类字段先求和
    IndustryRevenueTY_sum=('IndustryRevenueTY', 'sum'),
    IndustrySupplyTY_sum=('IndustrySupplyTY', 'sum'),
    IndustryDemandTY_sum=('IndustryDemandTY', 'sum'),
    # 统计唯一酒店数
    BrandCount=('Hotel Name', 'nunique')
)

# 对行业类字段执行除法修正
industry_columns = ['IndustryRevenueTY', 'IndustrySupplyTY', 'IndustryDemandTY']
for col in industry_columns:
    temp_df[col] = temp_df[f'{col}_sum'] / temp_df['BrandCount']

# 移除临时求和字段,得到最终结果
df_revPAR = temp_df.drop([f'{col}_sum' for col in industry_columns], axis=1)

优化优势

  • 减少一次groupby操作,大数据量下性能提升明显
  • 逻辑集中在一处,代码可读性、维护性更强
  • 避免两次分组后的数据对齐风险(如分组键不一致导致的匹配错误)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:15:27