如何将frozendict对象转换为pandas数据帧

2024-05-19 10:09:44 发布

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

我有以下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)

Tags: columnsinfromdataframepandasdataindexobject
2条回答

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

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

对于我来说,添加参数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

相关问题 更多 >

    热门问题