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

如何对DataFrame分组后将指定列分别转为List和Set

按Name分组转换DataFrame列格式

原始DataFrame

import pandas as pd

df = pd.DataFrame({
    'Name': ['ben', 'alex', 'linn', 'luke', 'alex', 'ben', 'ben'],
    'id': ['00005', '00006', '00007', '00009', '00001', '00002', '00003'],
    'other': ['abc', 'gf', 'jgj', 'gg', 'gf', 'abc', 'abc'],
    'list': [[1000, 'A', 90], [3000, 'B', 80], [600, 'C', 55], [5000, 'D', 88], [7000, 'R', 98], [9000, 'S', 28], [5000, 'T', 48]]
})

需求说明

按Name分组后:

  • id列转换为Set
  • list列转换为嵌套List
  • other列保留分组内的对应值(同一分组内other值一致)

解决方案

使用groupby结合agg方法实现分组聚合:

# 分组聚合
df1 = df.groupby('Name').agg(
    id=('id', set),
    other=('other', 'first'),  # 同一分组other值相同,取第一个即可
    list=('list', list)
).reset_index()

# 可选:调整id列的显示格式,与示例输出一致
df1['id'] = df1['id'].apply(lambda x: f"{{{', '.join(x)}}}")

print(df1)

输出结果

Name                id other                                               list
0   alex      {00006, 00001}    gf           [[3000, 'B', 80], [7000, 'R', 98]]
1    ben  {00005, 00002, 00003}   abc  [[1000, 'A', 90], [9000, 'S', 28], [5000, 'T', 48]]
2   linn           {00007}   jgj                    [[600, 'C', 55]]
3   luke           {00009}    gg                    [[5000, 'D', 88]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:25:17