gpt4 book ai didi

python - 将字典列表转换为数据框

转载 作者:行者123 更新时间:2023-12-04 00:15:03 24 4
gpt4 key购买 nike

我有一个字典列表,如下所示:

list_dict = [{'test1':{'a':1,'b':12,'c':40,'d':120,'e':20,'f':1,'g':2,'h':'2'}},
{'test2':{'a':5,'b':'10','c':20}},
{'test3':{'e':21,'f':'18','g':22,'h':20}}]

我想把它转换成这样的数据框:键应该以行的形式出现,测试应该以列的形式出现。并且如果测试没有其他测试中存在的键,则应将值填充为 NAN

    mac_type  test1  test2  test3
a 1 5 NAN
b 12 10 NAN
c 40 20 NAN
d 120 NAN NAN
e 20 NAN 21
f 1 NAN 18
g 2 NAN 22
h 2 NAN 20

请帮帮我。

最佳答案

使用带有扁平嵌套字典的字典理解并传递给 Dataframe 构造函数:

df = pd.DataFrame({k: v for x in list_dict for k, v in x.items()})
print (df)
test1 test2 test3
a 1 5 NaN
b 12 10 NaN
c 40 20 NaN
d 120 NaN NaN
e 20 NaN 21
f 1 NaN 18
g 2 NaN 22
h 2 NaN 20

或者为每个嵌套字典创建DataFrame并传递给concat ,如果大字典和许多外部键,这应该像第一个解决方案一样慢:

df = pd.concat([pd.DataFrame(x) for x in list_dict], axis=1)
print (df)
test1 test2 test3
a 1 5 NaN
b 12 10 NaN
c 40 20 NaN
d 120 NaN NaN
e 20 NaN 21
f 1 NaN 18
g 2 NaN 22
h 2 NaN 20

关于python - 将字典列表转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64694775/

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