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

如何将含字典列的pandas DataFrame展开为指定格式?

解决方法

步骤1:填充缺失的GameID和PlayID

原DataFrame中GameID和PlayID存在空值,先通过向前填充补全这些字段,确保每一行都有对应的关联标识:

import pandas as pd

# 假设原始数据存储在df中
df[['GameID', 'PlayID']] = df[['GameID', 'PlayID']].ffill()

步骤2:将字典转换为可展开的键值对列表

把dictionary列的每个字典转换成包含键值对元组的列表,让explode方法可以处理:

df['dictionary'] = df['dictionary'].apply(lambda x: list(x.items()))

步骤3:展开键值对并拆分列

用explode把列表展开为多行,再将元组拆分为playerId和opposingId两列,最后删除原字典列:

df = df.explode('dictionary')
df[['playerId', 'opposingId']] = pd.DataFrame(df['dictionary'].tolist(), index=df.index)
df = df.drop('dictionary', axis=1)

最终效果

执行完上述代码后,DataFrame会完全匹配你需要的格式:每个字典的键值对单独成行,同时保留对应的GameID、PlayID和FrameID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:20:41