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

如何将指定Dataframe转换为按分类聚合的字典列表?

问题:如何将指定Dataframe转换为分类字典列表?

原始Dataframe

keycategoryamount
2019-01abc123
2019-01xyz111
2019-02abc87
2019-02xyz34
2019-03abc15
2019-04def64

目标格式

[
  { "category": "abc", "2019-01": 123, "2019-02": 87, "2019-03": 15 },
  { "category": "xyz", "2019-01": 111, "2019-02": 34 },
  { "category": "def", "2019-04": 64 }
]

实现方法

嘿,这个需求用pandas就能很优雅地搞定,我给你两种实用的实现方式,都能得到你想要的结果:

方法1:分组遍历构建字典

这种方法逻辑直观,适合理解基础的分组操作:

import pandas as pd

# 构造示例Dataframe(如果你的数据已经是Dataframe可以跳过这步)
df = pd.DataFrame({
    'key': ['2019-01', '2019-01', '2019-02', '2019-02', '2019-03', '2019-04'],
    'category': ['abc', 'xyz', 'abc', 'xyz', 'abc', 'def'],
    'amount': [123, 111, 87, 34, 15, 64]
})

result = []
# 按category分组遍历
for category, group_data in df.groupby('category'):
    # 初始化当前分类的字典
    category_dict = {'category': category}
    # 把分组里的key和amount转成键值对,合并到字典中
    date_amount_dict = group_data.set_index('key')['amount'].to_dict()
    category_dict.update(date_amount_dict)
    # 添加到结果列表
    result.append(category_dict)

print(result)

方法2:透视表+字典转换

这种方法更简洁,利用pandas的透视表功能快速重塑数据:

import pandas as pd

df = pd.DataFrame({
    'key': ['2019-01', '2019-01', '2019-02', '2019-02', '2019-03', '2019-04'],
    'category': ['abc', 'xyz', 'abc', 'xyz', 'abc', 'def'],
    'amount': [123, 111, 87, 34, 15, 64]
})

# 透视表:以category为行,key为列,值为amount
pivot_df = df.pivot(index='category', columns='key', values='amount').reset_index()

# 遍历每一行,过滤空值后转成字典,再组成列表
result = pivot_df.apply(
    lambda row: {col: val for col, val in row.items() if pd.notna(val)},
    axis=1
).tolist()

print(result)

两种方法运行后都会输出你想要的字典列表,你可以根据自己的代码习惯选择其中一种~


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:02:39