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

Python如何展平含非统一结构JSON对象列的DataFrame

Pandas展平结构不统一的字典列实现方法

问题场景

DataFrame中存在一列存储结构不统一的字典(JSON对象):

  • 不同行的字典键不完全一致,部分键仅在部分行存在
  • 字典的所有值均为列表格式,部分键对应空列表[]

原始样例数据:

customer_id |    date    |             json_object
--------------------------------------------------------------------------
A101        | 2022-06-21 | {'name':['james'],'age':[55], 'hobby':['pubg']}
A102        | 2022-06-22 | {'name':['tarzan'],'status':[]}

需要展平为每行对应单个字典属性的结构,目标输出:

customer_id |    date    | attribute
---------------------------------------------
A101        | 2022-06-21 | 'name': 'james'
A101        | 2022-06-21 | 'age': 55
A101        | 2022-06-21 | 'hobby': 'pubg'
A102        | 2022-06-22 | 'name': 'tarzan'
A102        | 2022-06-22 | 'status':

实现代码

核心逻辑是逐行解析字典列,将每个键值对转换为目标格式的属性字符串,再通过explode将列表拆分为多行,无需提前枚举所有可能的属性名,自动兼容异构字典结构。

import pandas as pd

# 1. 构造测试数据
df = pd.DataFrame({
    'customer_id': ['A101', 'A102'],
    'date': ['2022-06-21', '2022-06-22'],
    'json_object': [
        {'name':['james'],'age':[55], 'hobby':['pubg']},
        {'name':['tarzan'],'status':[]}
    ]
})

# 2. 定义字典解析函数
def format_attr(dict_item):
    attr_col = []
    for key, val_list in dict_item.items():
        # 处理空列表:值留空
        if len(val_list) == 0:
            attr_col.append(f"'{key}':")
            continue
        # 处理非空列表:取第一个元素,字符串类型值加引号
        val = val_list[0]
        if isinstance(val, str):
            attr_col.append(f"'{key}': '{val}'")
        else:
            attr_col.append(f"'{key}': {val}")
    return attr_col

# 3. 展平得到结果
df['attribute'] = df['json_object'].apply(format_attr)
result = df.explode('attribute')[['customer_id', 'date', 'attribute']].reset_index(drop=True)

结果验证

执行print(result)即可得到完全匹配要求的输出结构:

customer_id        date     attribute
0        A101  2022-06-21  'name': 'james'
1        A101  2022-06-21        'age': 55
2        A101  2022-06-21  'hobby': 'pubg'
3        A102  2022-06-22  'name': 'tarzan'
4        A102  2022-06-22      'status':

补充说明

  • 如果字典值存在多元素列表的场景,可以调整解析逻辑,比如对多元素值做join拼接或者额外拆行
  • 如果属性值存在日期、布尔值等其他类型,只需要在format_attr函数中补充对应类型的格式化规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 19:48:28