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

如何将pandas DataFrame转换为指定格式的分组字典

实现步骤

你可以在现有代码基础上增加分组聚合后转字典的逻辑即可,完整可运行代码如下:

import pandas as pd

df = pd.read_csv(tests) 
df = df[['course_id','weight']]
# 核心转换逻辑
result = df.groupby('course_id')['weight'].apply(list).to_dict()
print(result)

逻辑说明

  • 调用groupby('course_id'):按照course_id列对整个DataFrame做分组,相同course_id的行会被归到同一个分组
  • 调用apply(list):将每个分组下的weight列的所有值,统一转换为列表格式
  • 调用to_dict():将分组聚合后得到的Series对象,直接转换为你需要的键为course_id、值为weight列表的字典结构

运行上述代码后,打印的result就是你要求的{1 : [10,40,50] , 2:[40,60] , 3 :[90,10]}格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:03