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

如何对DataFrame中存储字典列表的列执行透视转换操作

解决方案

直接用Pandas原生的数组拆分、JSON展开和透视表功能即可实现,不需要手动构造嵌套字典,代码如下:

import pandas as pd

# 提取所有非procedures字段作为索引维度
id_columns = [col for col in df.columns if col != "procedures"]

# 拆分procedures数组为每行一个procedure字典
df_exploded = df.explode("procedures", ignore_index=True)

# 展开procedure字典为单独列
df_procedure_cols = pd.json_normalize(df_exploded["procedures"])

# 合并原字段和展开后的procedure字段
df_combined = pd.concat([df_exploded.drop("procedures", axis=1), df_procedure_cols], axis=1)

# 透视生成多级列结果,自动对同procedure_key的数值求和
df_result = df_combined.pivot_table(
    index=id_columns,
    columns="procedure_key",
    values=["unit_count", "charges_amount_laboratory"],
    aggfunc="sum",
    fill_value=0
)

# 可选:调整列层级顺序,让同一个procedure_key的两个指标相邻,方便查看
df_result = df_result.swaplevel(axis=1).sort_index(axis=1)

说明

  1. 最终得到的df_result列是二级MultiIndex,第一级为procedure_key,第二级为对应的unit_count和charges_amount_laboratory,完全符合要求
  2. 你之前的方案手动构造了嵌套字典,后续需要额外拆分才能生成多级列,原生方法更简洁,也避免了手动写聚合逻辑的出错风险
  3. fill_value=0会把没有对应procedure的位置填0,不需要可以去掉,缺失值会显示为NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:45:04