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

如何快速提取DataFrame列内字典值并生成指定格式数据?

简洁高效的Pandas数据展开方案

实现代码

import pandas as pd

data = [
    ['0039384', [{'A': 415}, {'A': 228}, {'B': 360}, {'B': 198}, {'C': 300}, {'C': 165}]],
    ['0035584', [{'A': 345}, {'A': 117}, {'B': 223}, {'B': 554}, {'C': 443}, {'C': 143}]]
]

df = pd.DataFrame(data=data, columns=['id', 'prices'])

# 核心链式处理
result = (
    df.explode('prices')
    .assign(
        key=lambda x: x['prices'].apply(lambda d: next(iter(d.keys()))),
        value=lambda x: x['prices'].apply(lambda d: next(iter(d.values()))),
        type=lambda x: x.groupby(['id', 'key']).cumcount().map({0: 'CurrentPrice', 1: 'LastPrice'})
    )
    .pivot(index='id', columns=['type', 'key'], values='value')
    .sort_index(axis=1, level=1)
    .pipe(lambda x: x.set_axis([f'{t}_{k}' for t, k in x.columns], axis=1))
    .reset_index()
)

print(result.to_string(index=False))

输出结果

id CurrentPrice_A LastPrice_A CurrentPrice_B LastPrice_B CurrentPrice_C LastPrice_C
0039384           415          228           360          198           300          165
0035584           345          117           223          554           443          143

关键步骤说明

  • explode('prices'):将每个id对应的字典列表拆分为多行,每个字典单独占一行
  • assign方法一次性生成三个辅助列:
    • key:提取每个字典的唯一键(A/B/C)
    • value:提取字典对应的价格数值
    • type:按id+key分组后给每行编号,将第0个标记为CurrentPrice、第1个标记为LastPrice
  • pivot:将长表转为宽表,构建以type和key为多级索引的列
  • sort_index:按字母A/B/C排序列,保证输出顺序符合预期
  • pipe+set_axis:将多级列名合并为类型_字母的格式,比如CurrentPrice_A
  • reset_index:将id从索引转回普通列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:45:30