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

如何将包含DataFrame的Python字典展开为指定格式的独立数据行?

Python字典转统一DataFrame实现

首先需要提前导入依赖库:

import pandas as pd
import numpy as np

转换函数实现

def convert_struct_dict_to_df(dict_list):
    processed_dfs = []
    for single_dict in dict_list:
        # 取出当前字典内的summary数据框
        tmp_df = single_dict['summary'].copy()
        # 拼接公共字段
        tmp_df['mar'] = single_dict['mar']
        tmp_df['r'] = single_dict['params']['r']
        tmp_df['o'] = single_dict['params']['o']
        processed_dfs.append(tmp_df)
    # 合并所有子数据框并调整列顺序为需求格式
    result_df = pd.concat(processed_dfs, ignore_index=True)
    result_df = result_df.reindex(columns=['mar', 'r', 'o', 'year', 'customers', 'count'])
    return result_df

使用示例

将所有待转换的字典放到列表中传入函数即可:

# 你的示例数据
R1 = {
    'mar': 'BS',
    'summary': pd.DataFrame({
        "year": [2002, 2003],
        "customers": [400, 230],
        "count": [180, 115]}),
    'params': {
        'r': 1,
        'o': 4
    }
}

R2 = {
    'mar': 'NY',
    'summary': pd.DataFrame({
        "year": [2002, 2003],
        "customers": [410, 220],
        "count": np.array([180, 115])}),
    'params': {
        'r': 2,
        'o': 5
    }
}

# 调用函数
final_df = convert_struct_dict_to_df([R1, R2])
print(final_df)

运行后输出结果如下:

mar  r  o  year  customers  count
0  BS  1  4  2002        400    180
1  BS  1  4  2003        230    115
2  NY  2  5  2002        410    180
3  NY  2  5  2003        220    115

注:你给出的示例输出数值存在笔误,上述代码会严格按照输入字典的实际值生成对应结果,自动兼容summary中count为列表、numpy数组等不同格式的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:45:06