如何将Frozendict对象转换为熊猫数据框

时间:2018-09-25 06:52:53

标签: python pandas

我有以下Frozendict对象:

from frozendict import frozendict
my_object = frozendict({'Mn1': 3.9499512091579208, 'Gpsm1': 3.9499512091579208, 'Fam171a1': 3.029245020494556, 'Igfbp5': 6.642908688236191})

然后看起来像这样:

In [95]: my_object
Out[95]: <frozendict {'Mn1': 3.9499512091579208, 'Gpsm1': 3.9499512091579208, 'Fam171a1': 3.029245020494556, 'Igfbp5': 6.642908688236191}>

如何将其转换为熊猫数据框?

我尝试过但是失败了:

In [98]: import pandas as pd

In [99]: pd.DataFrame.from_dict(my_object)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-99-68a940d78eca> in <module>()
----> 1 pd.DataFrame.from_dict(my_object)

~/anaconda2/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in from_dict(cls, data, orient, dtype, columns)
    983             raise ValueError('only recognize index or columns for orient')
    984
--> 985         return cls(data, index=index, columns=columns, dtype=dtype)
    986
    987     def to_dict(self, orient='dict', into=dict):

~/anaconda2/envs/py36/lib/python3.6/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
    420                                          dtype=values.dtype, copy=False)
    421             else:
--> 422                 raise ValueError('DataFrame constructor not properly called!')
    423
    424         NDFrame.__init__(self, mgr, fastpath=True)

2 个答案:

答案 0 :(得分:1)

对我来说,添加参数orient='index'

df = pd.DataFrame.from_dict(my_object, orient='index')
print (df)
                 0
Mn1       3.949951
Gpsm1     3.949951
Fam171a1  3.029245
Igfbp5    6.642909

必要时还有参数columns

df = pd.DataFrame.from_dict(my_object, orient='index', columns=['col'])
print (df)
               col
Mn1       3.949951
Gpsm1     3.949951
Fam171a1  3.029245
Igfbp5    6.642909

答案 1 :(得分:1)

您可以指定orient='index'以使用字典键作为行来创建DataFrame:

pd.DataFrame.from_dict(my_object, orient='index')