gpt4 book ai didi

python - 转换数据框中的嵌套字典?

转载 作者:行者123 更新时间:2023-12-01 08:20:13 25 4
gpt4 key购买 nike

我一直在尝试解析数据框中的嵌套字典。我从 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'}]

最佳答案

我无法退出“第三”列中嵌套字典的格式,但这是我建议使用 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 清理它并转换为一个函数,但这应该可以满足您的具体情况。

关于python - 转换数据框中的嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com