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

如何从DataFrame行的字典列表中提取值并拆分列

问题:拆分DataFrame中嵌套字典列表为多列

现有如下DataFrame:

id        features                             
    100     [{'city': 'Rio'},  {'destination': '2'}]        
    110     [{'city': 'Sao Paulo'}]     
    135     [{'city': 'Recife'}, {'destination': '45'}]
    145     [{'city': 'Munich'}, {'destination': '67'}]
    167     [{'city': 'Berlin'}, {'latitude':'56'}, {'longitude':'30'}]

需要将features列中的字典键作为列名、值作为对应列的数据,拆分得到如下格式的DataFrame:

id      city          destination   latitude       longitude                            
    100     'Rio'          '2'            NaN            NaN  
    110     'Sao Paulo'    NaN            NaN            NaN  
    135     'Recife'       '45'           NaN            NaN  
    145     'Munich'       '67'           NaN            NaN  
    167     'Berlin'       NaN            '56'           '30'

尝试的方法及问题

  • 方法一:
df = df.explode('features').reset_index(drop = True)
result = pd.concat([df.drop(columns='features'), 
           pd.json_normalize(df['features'])], axis=1)

结果仅保留了id列,原因是explode后每个id对应多行,json_normalize生成的列在不同行只有单个值、其余为NaN,未做聚合导致最终其他列全为NaN。

  • 方法二:
df = df.explode('features').reset_index(drop = True)
df2 = df.set_index('id')
df2 = df2['features'].astype('str')
df2 = df2.apply(lambda x: ast.literal_eval(x))
df2 = df2.apply(pd.Series)
result = df2.reset_index()

结果接近需求,但同一id对应多行数据,需进一步合并处理。


解决方案

方案一:直接合并字典后拆分(推荐)

无需explode,先把每个features列表中的多个字典合并为单个字典,再拆分对应列:

import pandas as pd

# 合并每个features列表内的所有字典为一个字典
df['features'] = df['features'].apply(lambda x: {k: v for d in x for k, v in d.items()})
# 拆分字典为列,与原id列合并
result = pd.concat([df['id'], pd.json_normalize(df['features'])], axis=1)

方案二:调整方法二,添加分组聚合

针对方法二得到的多行结果,按id分组并保留每个列的非空值:

import pandas as pd
import ast

df = df.explode('features').reset_index(drop=True)
df2 = df.set_index('id')
df2 = df2['features'].astype('str').apply(ast.literal_eval).apply(pd.Series)
# 按id分组,取每个列的第一个非空值
result = df2.groupby('id').first().reset_index()

两种方案都能得到目标格式的DataFrame,方案一无需处理多行聚合,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:33:23