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

如何将pandas DataFrame转换为字典列表组成的嵌套字典

多层索引DataFrame转指定结构字典实现

需求说明

现有多层索引Pandas DataFrame,结构如下:

end_hour  start_hour  values
level_0 level_1         
FRIDAY  0        6          0   {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}
        1       10          6   {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}
        2       24         10   {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}
MONDAY  0        6          0   {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}
        1       10          6   {'onDemandTripBase': 4.7,'tripMoving': 1.2,'tripWaiting': 19.1}
        2       24         10   {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}

需转换为如下格式的字典:

{'FRIDAY': [{'end_hour': 6,'start_hour': 0,'values':{'onDemandTripBase':4.269,'tripMoving': 1.086,'tripWaiting': 17.375}},
  {'end_hour': 10,
   'start_hour': 6,
   'values': {'onDemandTripBase': 4.7,
    'tripMoving': 1.2,
    'tripWaiting': 19.1}},
  {'end_hour': 24,
   'start_hour': 10,
   'values': {'onDemandTripBase': 4.269,
    'tripMoving': 1.086,
    'tripWaiting': 17.375}}],
'MONDAY': [{'end_hour': 6,
  'start_hour': 0,
   'values': {'onDemandTripBase': 4.269,
    'tripMoving': 1.086,
    'tripWaiting': 17.375}},
  {'end_hour': 10,
   'start_hour': 6,
   'values': {'onDemandTripBase': 4.7,
    'tripMoving': 1.2,
    'tripWaiting': 19.1}},
  {'end_hour': 24,
   'start_hour': 10,
   'values': {'onDemandTripBase': 4.269,
    'tripMoving': 1.086,
    'tripWaiting': 17.375}}]
}

直接使用.to_dict('index')生成的字典键为元组类型,不符合格式要求。

实现代码

# 假设DataFrame变量名为df
result = {
    day: group.droplevel(level=1).to_dict("records")
    for day, group in df.groupby(level=0)
}

逻辑说明

  • 调用groupby(level=0)按多层索引的第一级(FRIDAY、MONDAY等星期标识)拆分数据集
  • droplevel(level=1)移除第二层数字索引,避免冗余索引字段进入最终结果
  • to_dict("records")将分组内的每一行转换为独立字典,按原行顺序组成列表,完全匹配目标结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:12:17