如何提取Pandas DataFrame列表嵌套字典列的指定字段生成结构化新列
解决方案
运行以下代码即可得到你需要的输出格式:
import pandas as pd # 原始DataFrame构造 df = pd.DataFrame({ 'info':[1.4,3.6,6.5], 'new':[ [{'score':0.998, 'letters':'C', 'temp':1}, {'score':1.343, 'letters':'B', 'temp':0}, {'score':2.323, 'letters':'F', 'temp':1}], [{'score':2.532, 'letters':'D', 'temp':1}, {'score':2.123, 'letters':'G', 'temp':1}, {'score':4.332, 'letters':'S', 'temp':0}], [{'score':2.223, 'letters':'C', 'temp':0}, {'score':1.144, 'letters':'J', 'temp':1}, {'score':7.443, 'letters':'G', 'temp':9}] ] }) # 核心处理逻辑 # 1. 把new列的每个列表拆分为多列,每列对应列表中第N个字典 split_new = df['new'].apply(pd.Series) temp_dfs = [] for idx, col in split_new.items(): # 2. 提取每个字典的目标字段,给列名加上位置序号 normalized_col = pd.json_normalize(col)[['score', 'letters']] normalized_col.columns = [f'{field}{idx+1}' for field in normalized_col.columns] temp_dfs.append(normalized_col) # 3. 拼接原始info列和处理好的字段列 result = pd.concat([df[['info']]] + temp_dfs, axis=1) print(result)
原有代码问题说明
- 第一种方案错误点:
[x[0] for x in df['new']]只提取了每个列表中的第一个字典,只能得到第一组score和letters值,丢失了后续位置的数据 - 第二种方案错误点:用
{i['score']: i['letters'] for i in x}构造Series时,把score数值作为列名,不符合要求的score1/score2固定序号命名格式,结构完全不符合预期
内容的提问来源于stack exchange,提问作者Chip
相关产品推荐
相关产品推荐

