首页 > 解决方案 > 在数据框中转换嵌套字典?

问题描述

我一直在尝试解析数据框中的嵌套字典。我从 dict 制作了这个 df,但无法弄清楚这个嵌套的。

df

    First   second    third              

 0     1       2      {nested dict}

嵌套字典:

   {'fourth': '4', 'fifth': '5', 'sixth': '6'}, {'fourth': '7', 'fifth': '8', 'sixth': '9'}

我想要的输出是:

        First   second  fourth   fifth   sixth   fourth   fifth   sixth          

 0     1       2       4         5        6         7       8       9

编辑:原始字典

   'archi': [{'fourth': '115',
      'fifth': '-162',
      'sixth': '112'},
     {'fourth': '52',
      'fifth': '42',
      'sixth': ' 32'}]

标签: pythonpandasdataframe

解决方案


我不能退出告诉“第三”列中嵌套 dict 的格式,但这是我建议使用Python 的方法:Pandas dataframe from Series of dict作为起点。这是一个可重现的字典和数据框:

nst_dict = {'archi': [{'fourth': '115', 'fifth': '-162', 'sixth': '112'},
      {'fourth': '52', 'fifth': '42','sixth': ' 32'}]}

df = pd.DataFrame.from_dict({'First':[1,2], 'Second':[2,3], 
     'third': [nst_dict,nst_dict]})

然后你需要首先访问字典中的列表,然后是列表中的项目:

df.thrd_1 = df.third.apply(lambda x: x['archi']) # convert to list
df.thrd_1a = df.thrd_1.apply(lambda x: x[0]) # access first item
df.thrd_1b = df.thrd_1.apply(lambda x: x[1]) # access second item

out = df.drop('third', axis=1).merge(
    df.thrd_1a.apply(pd.Series).merge(df.thrd_1a.apply(pd.Series),
    left_index=True, right_index=True),
    left_index=True, right_index=True)

print(out)

First  Second fourth_x fifth_x sixth_x fourth_y fifth_y sixth_y
0      1       2      115    -162     112      115    -162     112
1      2       3      115    -162     112      115    -162     112

我会尝试用它来清理它collections.abc并变成一个函数,但这应该可以解决你的具体情况。


推荐阅读