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

如何将嵌套字典列表转换为指定格式的Pandas DataFrame

解决嵌套字典列表转特定格式Pandas DataFrame的问题

直接用pd.DataFrame(order)转换时,line_items列会保留原始的字典列表结构,无法得到你需要的多行键值对格式。你需要对line_items字段做针对性的格式化处理,具体步骤如下:

1. 定义格式化函数

这个函数负责把每个订单下的商品字典列表,转换成你需要的多行键值对字符串:

import pandas as pd

def format_line_items(items):
    line_strings = []
    # 遍历每个商品字典,提取键值对并格式化为指定字符串
    for item in items:
        for key, val in item.items():
            line_strings.append(f"{key}: {val}")
    # 用带缩进的换行符连接所有字符串,匹配示例的排版格式
    return '\n                              '.join(line_strings)

2. 处理原始数据生成目标DataFrame

order = [
    {
        'order_id': 1,
        'status': 'processing',
        'line_items': [
            {'product_id': 2, 'product_name': 'mango'},
            {'product_id': 4, 'product_name': 'orange'}
        ]
    },
    {
        'order_id': 2,
        'status': 'processing',
        'line_items': [
            {'product_id': 3, 'product_name': 'banana'}
        ]
    }
]

# 先转换为基础DataFrame
df_order = pd.DataFrame(order)
# 对line_items列应用格式化函数
df_order['line_items'] = df_order['line_items'].apply(format_line_items)

# 设置显示选项,确保换行内容完整展示
pd.set_option('display.max_colwidth', None)
print(df_order)

执行后会输出你预期的格式:

order_id     status                                                                 line_items
0         1  processing  product_id: 2\n                              product_name: mango\n                              product_id: 4\n                              product_name: orange
1         2  processing                     product_id: 3\n                              product_name: banana

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:18:10