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

如何在Pandas中通过单次groupby同时实现size统计与sum求和?

问题描述

我有一个房屋数据的DataFrame,每行代表一套房屋,数据如下:

data = [
  ['Oxford', 2016, True],
  ['Oxford', 2016, True],
  ['Oxford', 2018, False],
  ['Cambridge', 2016, False],
  ['Cambridge', 2016, True]
]
df = pd.DataFrame(data, columns=['town', 'year', 'is_detached'])

对应的DataFrame输出:

town  year  is_detached
0     Oxford  2016         True
1     Oxford  2016         True
2     Oxford  2018        False
3  Cambridge  2016        False
4  Cambridge  2016         True

我希望得到如下格式的统计表格:

town  total_houses_2016  total_houses_2018  is_detached_2016  is_detached_2018
0     Oxford                  2                  1                 2                 0
1  Cambridge                  2                  0                 1                 0

目前我通过两次独立的groupby操作,再将结果合并来实现:

by_town_totals = df.groupby([df.town, df.year])\
    .size()\
    .reset_index()\
    .pivot(index=["town"], columns="year", values=0).fillna(0)\
    .add_prefix('total_houses_')
by_town_detached = df.groupby([df.town, df.year])\
    .is_detached.sum().reset_index()\
    .pivot(index=["town"], columns="year", values="is_detached").fillna(0)\
    .add_prefix('is_detached_')
by_town = pd.concat([by_town_totals, by_town_detached], axis=1).reset_index()

请问是否可以通过单次groupby操作完成上述需求?

解决方案

当然可以用单次groupby操作实现,核心思路是在分组后同时计算两个聚合指标(总房屋数、独栋房屋数),再通过结构重塑得到目标格式。

具体实现代码如下:

# 按town和year分组,同时计算总房屋数和独栋房屋数
agg_result = df.groupby(['town', 'year']).agg(
    total_houses=('town', 'size'),
    is_detached=('is_detached', 'sum')
).unstack(fill_value=0)

# 调整多级列名为目标格式
agg_result.columns = [f'{col[0]}_{col[1]}' for col in agg_result.columns]

# 重置索引,将town转为普通列
final_df = agg_result.reset_index()

执行后得到的结果与预期一致:

town  total_houses_2016  total_houses_2018  is_detached_2016  is_detached_2018
0  Cambridge                  2                  0                 1                 0
1     Oxford                  2                  1                 2                 0

代码说明

  1. groupby+agg:一次分组同时指定两个聚合规则,total_houses用size统计每组房屋总数,is_detached用sum统计独栋数量(布尔值True等价于1,False等价于0)。
  2. unstack:将year从行索引转为列维度,用fill_value=0填充无数据的年份(比如Cambridge的2018年)。
  3. 列名调整:把unstack生成的多级列名(如('total_houses', 2016))合并为total_houses_2016的格式。
  4. reset_index:将town从索引转回普通列,匹配目标表格的结构。

这样就无需两次分组再合并,单次操作即可完成需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:03:36