gpt4 book ai didi

python - 将我的字典变成 pandas 数据框

转载 作者:行者123 更新时间:2023-12-01 22:40:32 25 4
gpt4 key购买 nike

我有一个函数,可以根据某些条件创建多个字典的字典。

但是,我真的很想在收集后将字典转换为数据框。但我找不到一个简单的方法来做到这一点......现在我认为解决方案是将字典中的每个键乘以最内部字典中的键的数量,但希望有更好的方法

由于我的函数创建了字典,如果有更好的方法,我可以以任何方式更改它。

这是我现在的字典

{'TSLA': {2011: {'negative': {'lowPrice': 185.16,
'lowDate': '05/27/19',
'highPrice': 365.71,
'highDate': '12/10/18',
'change': -0.49}},
2012: {'negative': {'lowPrice': 185.16,
'lowDate': '05/27/19',
'highPrice': 365.71,
'highDate': '12/10/18',
'change': -0.49}},
2013: {'negative': {'lowPrice': 32.91,
'lowDate': '01/07/13',
'highPrice': 37.24,
'highDate': '03/26/12',
'change': -0.12},
'positive': {'lowPrice': 32.91,
'lowDate': '01/07/13',
'highPrice': 190.9,
'highDate': '09/23/13',
'change': 4.8}}}}

我想要的输出是这样的,当然具有以下值:

                    lowPrice lowDate highPrice highDate change
ATVI 2012 Negative NaN NaN NaN NaN NaN
Positive NaN NaN NaN NaN NaN
2013 Negative NaN NaN NaN NaN NaN
TSLA 2014 Positive NaN NaN NaN NaN NaN
2012 Negative NaN NaN NaN NaN NaN
2013 Positive NaN NaN NaN NaN NaN
2014 Positive NaN NaN NaN NaN NaN

最佳答案

您可以将键元组的嵌套字典展平 2 次,然后传递给 DataFrame.from_dict :

d1 = {(k1, k2, k3): v3 
for k1, v1 in d.items()
for k2, v2 in v1.items()
for k3, v3 in v2.items()}

df = pd.DataFrame.from_dict(d1, orient='index')
#alternative
#df = pd.DataFrame(d1).T
<小时/>
print (df)
lowPrice lowDate highPrice highDate change
TSLA 2011 negative 185.16 05/27/19 365.71 12/10/18 -0.49
2012 negative 185.16 05/27/19 365.71 12/10/18 -0.49
2013 negative 32.91 01/07/13 37.24 03/26/12 -0.12
positive 32.91 01/07/13 190.9 09/23/13 4.8

关于python - 将我的字典变成 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59910697/

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