You need to enable JavaScript to run this app. 将含嵌套字典和列表的Python字典扁平化后转为pandas DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

将含嵌套字典和列表的Python字典扁平化后转为pandas DataFrame

实现方法

直接按规则展开嵌套字典即可,列表字段无需额外处理,pandas会自动将整个列表作为单个单元格值存储,完整代码如下:

import pandas as pd

# 原始字典
result_dict = { 'kontonummer': None,
                'industryPredictions': {'Supermarket': 0.006795256825841207,
                                        'Cars': 0.01113155396585519},
                'paymentmethods': ['Klarna SofortUeberweisung',
                                   'Klarna Ratenkauf.',
                                   'Ueberweisung'],
                'pricesAmount': 2721,
                'pricesMean': 30.796045571481077,
                'pricesQ25': 12.99}

# 扁平化字典处理
flattened = {}
for key, value in result_dict.items():
    # 处理嵌套的industryPredictions字典
    if isinstance(value, dict):
        for sub_key, sub_value in value.items():
            flattened[f"{key}.{sub_key}"] = sub_value
    # 其余字段(包括列表类型的paymentmethods)直接保留
    else:
        flattened[key] = value

# 转换为DataFrame,注意外层套列表保证按行生成
df = pd.DataFrame([flattened])

# 可选:按示例要求调整数值精度
df = df.round({
    "industryPredictions.Supermarket": 6,
    "industryPredictions.Cars": 6,
    "pricesMean": 2
})

输出的df结构完全匹配要求,paymentmethods字段会将整个列表作为单元格值存储,嵌套字段也会按照「父键.子键」的格式生成列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 00:27:03