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

如何将Pandas DataFrame中嵌套字典的value键值转为行值?

问题描述

给定如下嵌套结构的DataFrame:

{'index': {0: 0, 1: 1},
 'speed': {0: {'value': ['3'], 'comment': ''},
  1: {'value': ['2'], 'comment': ''}},
 'rotor': {0: {'value': ['2'], 'comment': ''},
  1: {'value': ['3'], 'comment': ''}}}

需要提取嵌套字典中value键对应的内容(并转为整数),得到目标DataFrame:

pd.DataFrame({'index': [0,1],'speed': [3,2],'rotor': [2,3]})

尝试使用df.apply(lambda x: x.get('value'))和df.apply(lambda x: x.get('value'), axis=1)均未成功,求可行解决方法。

解决方法

方法1:逐列处理目标字段

index列是普通数值无需改动,仅针对speed、rotor这类嵌套字典列处理:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'index': {0: 0, 1: 1},
    'speed': {0: {'value': ['3'], 'comment': ''}, 1: {'value': ['2'], 'comment': ''}},
    'rotor': {0: {'value': ['2'], 'comment': ''}, 1: {'value': ['3'], 'comment': ''}}
})

# 提取value列表的首个元素并转为整数
for col in ['speed', 'rotor']:
    df[col] = df[col].apply(lambda x: int(x['value'][0]))

方法2:批量处理嵌套字段

如果有多个同结构的嵌套列,可直接选中这些列用applymap批量转换:

df[['speed', 'rotor']] = df[['speed', 'rotor']].applymap(lambda x: int(x['value'][0]))

方法3:逐行处理全量字段

如果想用axis=1的apply,需要明确指定每一列的处理逻辑:

df = df.apply(lambda row: pd.Series({
    'index': row['index'],
    'speed': int(row['speed']['value'][0]),
    'rotor': int(row['rotor']['value'][0])
}), axis=1)

原方法失败原因

  • df.apply(lambda x: x.get('value'))默认按列处理,每一列是Series对象,调用get('value')会试图从Series中取value键,显然不存在,返回NaN。
  • df.apply(lambda x: x.get('value'), axis=1)按行处理时,每一行是Series,x.get('value')会查找行中名为value的列,而数据里没有该列,同样返回NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:55:16