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

Pandas将DataFrame转换为指定层级嵌套字典的实现方案咨询

问题描述

我有如下DataFrame:

Month_Year  City_Name   Chain_Name Product_Name Product_Price
11-2021     London      Aldi       Pasta        2.33
11-2021     Bristol     Spar       Bananas      1.45
10-2021     London      Tesco      Olives       4.12
10-2021     Cardiff     Spar       Pasta        2.25

我需要把数据按「月份→城市→超市→商品价格」的层级做成嵌套可折叠控件,希望将DataFrame转换为对应的嵌套结构。
之前找到的递归groupby转嵌套字典的方案因为字典不支持重复键无法使用,我的数据各列都可能存在重复值,不确定字典是不是该场景的最优解,也考虑过树结构但不知道怎么实现,请问有什么可行方案?

解决方案

下面给出两种适配不同场景的实现方案:

方案1:嵌套defaultdict(适合本地数据处理场景)

用collections.defaultdict构造递归嵌套字典,天然支持同层级多键值写入,也可以适配同个商品对应多个价格的场景:

import pandas as pd
from collections import defaultdict

# 递归嵌套字典工厂函数
def nested_dict():
    return defaultdict(nested_dict)

result = nested_dict()
for _, row in df.iterrows():
    month = row["Month_Year"]
    city = row["City_Name"]
    shop = row["Chain_Name"]
    product = row["Product_Name"]
    price = row["Product_Price"]
    # 确定同个超市下不会有重复商品名可以直接赋值
    # result[month][city][shop][product] = price
    # 兼容同个商品多个价格的场景,用列表存储
    if product not in result[month][city][shop]:
        result[month][city][shop][product] = []
    result[month][city][shop][product].append(price)

方案2:树形列表结构(适合对接前端折叠控件场景)

如果要对接主流UI组件库的折叠树组件,更推荐转成带children属性的列表结构,完全不存在重复键冲突问题,不需要额外转换就能直接传入组件使用:

def build_tree(df, level_cols, value_col):
    # 到最后一级直接返回键值对
    if len(level_cols) == 1:
        return [{"name": row[level_cols[0]], "value": row[value_col]} for _, row in df.iterrows()]
    current_col = level_cols[0]
    next_cols = level_cols[1:]
    tree = []
    for key, group in df.groupby(current_col):
        tree.append({
            "name": key,
            "children": build_tree(group, next_cols, value_col)
        })
    return tree

# 按层级顺序传入列名即可生成对应嵌套树
nested_tree = build_tree(df, ["Month_Year", "City_Name", "Chain_Name", "Product_Name"], "Product_Price")

输出结构示例如下:

[
  {
    "name": "10-2021",
    "children": [
      {
        "name": "Cardiff",
        "children": [
          {
            "name": "Spar",
            "children": [{"name": "Pasta", "value": 2.25}]
          }
        ]
      },
      {
        "name": "London",
        "children": [
          {
            "name": "Tesco",
            "children": [{"name": "Olives", "value": 4.12}]
          }
        ]
      }
    ]
  }
]

选择建议

  • 仅本地做数据处理、自定义渲染逻辑选方案1,读写效率更高
  • 对接前端组件库选方案2,适配性更强,完全规避重复键问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:01