我有一个如下所示的数据集(在数据框中):
**_id** **paper_title** **references** **full_text** 1 XYZ [{'abc':'something','def':'something'},{'def':'something'},...many others] something 2 XYZ [{'abc':'something','def':'something'},{'def':'something'},...many others] something 3 XYZ [{'abc':'something'},{'def':'something'},...many others] something
期望的结果:
**_id** **paper_title** **abc** **def** **full_text** 1 XYZ something something something something something . . (根据_id列展开列表中的所有字典) 2 XYZ something something something something something . . (根据_id列展开列表中的所有字典)
我尝试过使用df['column_name'].apply(pd.Series).apply(pd.Series)
来将列表和字典拆分成数据框的列,但这并没有帮助,因为它没有拆分字典。
数据框的第一行:df.head(1)
回答:
在阅读了大量的Pandas文档后,我发现使用explode方法和apply(pd.Series)结合是最简单的方法,这正是我在问题中所寻找的。
以下是代码:
df = df.explode('reference')
# 它将列表展开为子集列的行
df = df['reference'].apply(pd.Series).merge(df, left_index=True, right_index=True, how ='outer')
# 将数据框单元格内的列表拆分为行,并与原始数据框合并,类似于集合论中的(AUB)
附注:合并时需注意列中的唯一值,因为会有许多列包含重复的值
希望这能帮助到那些在数据框/系列中处理包含多个字典的列表,并希望将多个字典的键拆分到新列中,值作为行的用户。