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

如何按pandas DataFrame指定列分组,将其他列聚合为字典列表

解决方法

有两种常用的简洁实现方式,都可以直接得到目标结果:

方式1:单步聚合写法

import pandas as pd

# 构造输入数据
df = pd.DataFrame([["Foo Burgers", "Burgers and Fries", "New York"], 
                   ["Cheesy's", "Cheeseburgers", "New York"],
                   ["Buggy Burgers", "Insect Burgers", "London"],
                   ["Fry Guy", "Fries", "London"],
                   ["Beermania", "Beer", "Munich"]], columns=["Name","Menu","City"])

# 核心转换代码
goal_df = df.groupby('City', as_index=False).apply(
    lambda x: x.drop('City', axis=1).to_dict('records')
).rename(columns={None: 'Restaurants'})

方式2:分步逻辑写法(更易理解)

# 第一步:先把需要打包的字段转成每行一个字典
df['Restaurants'] = df[['Name', 'Menu']].to_dict('records')
# 第二步:按城市分组,把同一城市的字典列表聚合
goal_df = df.groupby('City', as_index=False)['Restaurants'].agg(list)

两种写法的输出结果和你给出的goal_df完全一致。如果后续要换分组列或者调整需要打包的字段,只要修改对应列名即可。

小技巧:如果需要打包分组列之外的所有字段,不需要手动罗列列名,把上面代码里的[['Name', 'Menu']]替换成df[df.columns.difference(['City'])]即可自动适配多列场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:36:03