如何从python字典创建pandas数据帧?

2024-05-16 03:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面有一本python字典:

dict = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)};

我想把字典改成数据帧,比如:

enter image description here

如何编写代码?在

我使用:

^{pr2}$

但它会出错的。 有人能帮忙吗?在


Tags: 数据代码字典dictpr2stock1stock2stock3
2条回答

如果问题过于复杂,只需将字典传递给DataFrame构造函数:

import pandas as pd

d = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)}
print(pd.DataFrame(d))

印刷品:

^{pr2}$

试试这个:不要将变量命名为python关键字!

dd = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)};
#pd.DataFrame(dd) Should work!

pd.DataFrame.from_dict(dd, orient='columns')

   stock1  stock2  stock3
0       5       1       7
1       6       2       8
2       7       3       9

相关问题 更多 >