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
相关产品推荐
相关产品推荐

