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

如何展平pandas中JSON格式列生成新行并保留对应order_id

数据表JSON列展平实现方案

pandas 标准实现

之前调用explode和json_normalize()未得到预期结果,核心原因是两个方法没有配合使用,或是JSON列存储格式为字符串、未提前转换为Python原生列表对象,以下是可直接运行的完整代码:

import pandas as pd
import json

# 此处替换为你的原始数据读取逻辑
df = pd.DataFrame({
    "order_id": [1,2,3,4],
    "JSON": [
        '[{"key": "100", "product": "soap"},{"key": "104", "product": "butter"}]',
        '[{"key": "97", "product": "baby wipes"},{"key": "104", "product": "butter"},{"key": "107", "product": "milk"}]',
        '[{"key": "95", "product": "diapers"},{"key": "104", "product": "butter"},{"key": "110", "product": "toothpaste"}]',
        '[{"key": "100", "product": "soap"},{"key": "101", "product": "yogurt"},{"key": "111", "product": "hair brush"},{"key": "112", "product": "hair dye"}]'
    ]
})

# 步骤1:若JSON列是字符串格式,先转为Python列表;若列内已是列表类型可跳过此步
df["JSON"] = df["JSON"].apply(json.loads)

# 步骤2:用explode将数组内的每个字典拆为独立行
df_exploded = df.explode("JSON", ignore_index=True)

# 步骤3:将字典拆分为独立的key、product列,和order_id拼接得到最终结果
df_result = pd.concat(
    [df_exploded.drop(columns="JSON"), pd.json_normalize(df_exploded["JSON"])],
    axis=1
)

执行后得到的df_result完全匹配预期结构:共3列order_id/key/product,单个商品对应一行数据。

常见失效原因

  • 未做格式转换:从CSV、数据库导出的JSON列默认是字符串类型,直接调用explode会把整段字符串识别为单个元素,无法拆分数组
  • 仅单独调用一个方法:单独用explode只能把数组拆成每行一个字典,字典内的字段不会自动拆为列;单独对原始列调用json_normalize会丢失order_id的关联关系,导致行匹配错位
  • 未设置ignore_index=True:拆分后索引重复,后续拼接容易出现行数不匹配问题

非pandas实现方案

如果不需要依赖pandas特性,直接遍历原始数据展平逻辑更简单,不容易出错:

# 替换为你的原始数据源
raw_data = [
    {"order_id":1, "JSON": [{'key': '100', 'product': 'soap'},{'key': '104', 'product': 'butter'}]},
    {"order_id":2, "JSON": [{'key': '97', 'product': 'baby wipes'},{'key': '104', 'product': 'butter'},{'key': '107', 'product': 'milk'}]},
    {"order_id":3, "JSON": [{'key': '95', 'product': 'diapers'},{'key': '104', 'product': 'butter'},{'key': '110', 'product': 'toothpaste'}]},
    {"order_id":4, "JSON": [{'key': '100', 'product': 'soap'},{'key': '101', 'product': 'yogurt'},{'key': '111', 'product': 'hair brush'},{'key': '112', 'product': 'hair dye'}]}
]

result = []
for row in raw_data:
    for item in row["JSON"]:
        result.append({
            "order_id": row["order_id"],
            "key": item["key"],
            "product": item["product"]
        })

# 如需转pandas表直接传入pd.DataFrame(result)即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:33:29