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

Python:将DataFrame中JSON结构列展开为多列

如何展开DataFrame中包含JSON数组的列?

嘿,这个需求在处理嵌套数据时特别常见,用Pandas就能轻松搞定!这里给你两种实用的方法,按需选择就行:

方法1:直接提取字典后解析(适合单元素数组)

因为你的Data列里每个单元格都是只有一个JSON对象的数组,我们可以先把数组里的字典取出来,再用json_normalize把字典拆成列,最后和原表的ClientToken合并:

import pandas as pd

# 模拟你的原始DataFrame
df = pd.DataFrame({
    'ClientToken': ['7a9ee887-8a09-ff9592e08245', 'bac49563-2cf0-cb08e69daa48'],
    'Data': [
        [{"summaryId":"4814223456","duration":952,"startTime":1587442919}],
        [{"summaryId":"4814239586","duration":132,"startTime":1587443876}]
    ]
})

# 提取数组中的单个字典,解析成列
parsed_df = pd.json_normalize(df['Data'].str[0])
# 合并ClientToken和解析后的列
final_df = pd.concat([df['ClientToken'], parsed_df], axis=1)

print(final_df)

运行后就能得到你想要的结构:

ClientToken   summaryId  duration   startTime
0  7a9ee887-8a09-ff9592e08245  4814223456       952  1587442919
1  bac49563-2cf0-cb08e69daa48  4814239586       132  1587443876

方法2:先展开数组再解析(通用型)

如果以后你的Data列里可能出现包含多个JSON对象的数组,用这种方法更稳妥——先通过explode把数组拆成多行(每个JSON对象一行),再解析字典:

import pandas as pd

# 同样模拟原始DataFrame
df = pd.DataFrame({
    'ClientToken': ['7a9ee887-8a09-ff9592e08245', 'bac49563-2cf0-cb08e69daa48'],
    'Data': [
        [{"summaryId":"4814223456","duration":952,"startTime":1587442919}],
        [{"summaryId":"4814239586","duration":132,"startTime":1587443876}]
    ]
})

# 展开数组,每个JSON对象单独一行
exploded_df = df.explode('Data', ignore_index=True)
# 解析字典成列
parsed_df = pd.json_normalize(exploded_df['Data'])
# 合并列
final_df = pd.concat([exploded_df['ClientToken'], parsed_df], axis=1)

print(final_df)

这个方法的好处是,哪怕某一行的Data数组里有3个JSON对象,也会自动拆成3行,对应同一个ClientToken,扩展性拉满!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:47:51