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

Pandas解析API返回的列表字典数据 实现数组字段拆分为多行

方案1:使用Pandas内置explode方法(推荐,代码最简)

explode是Pandas专门用于将列中的列表元素拆分为多行的方法,其余列会自动复用当前行的其他值:

import pandas as pd

# 你原有代码无需修改,直接使用API返回的response
response =[{'type': 'heartrate', 
    'data': [27, 32, 35, 31, 29, 30],
    'education':  'bachelor',
    'salary': 80000}]
df = pd.DataFrame(response)

# 新增这一行即可完成展开
df = df.explode('data', ignore_index=True)

输出结果和你要求的完全一致。

方案2:预处理原始响应数据(兼容低版本Pandas)

如果你的Pandas版本低于0.25(该版本才新增explode方法),可以提前对API返回的原始数据做结构转换,无需修改API输出:

import pandas as pd

response =[{'type': 'heartrate', 
    'data': [27, 32, 35, 31, 29, 30],
    'education':  'bachelor',
    'salary': 80000}]

# 预处理展开数据
processed_list = []
for entry in response:
    # 取出当前条目的data列表
    data_values = entry.pop('data')
    # 遍历列表每个值,生成独立条目
    for val in data_values:
        temp_entry = entry.copy()
        temp_entry['data'] = val
        processed_list.append(temp_entry)

df = pd.DataFrame(processed_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 08:51:02