How to retrieve pandas df multiindex from HDFStore?

情到浓时终转凉″ 提交于 2019-12-13 05:06:22

问题


If DataFrame with simple index is the case, one may retrieve index from HDFStore as follows:

df = pd.DataFrame(np.random.randn(2, 3), index=list('yz'), columns=list('abc'))
df

>>>      a          b           c
>>> y   -0.181063   1.919440    1.550992
>>> z   -0.701797   1.917156    0.645707
with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    y
>>> 1    z
>>> Name: index, dtype: object

As stated in the docs.

But in case with MultiIndex such trick doesn't work:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1            
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681

More precisely it returns wrong index:

with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select_column('df', 'index')

>>> 0    0
>>> 1    1
>>> Name: index, dtype: int64

How to retrieve correct DataFrame MultiIndex?


回答1:


One may use select with columns=['index'] parameter specified:

df = pd.DataFrame(np.random.randn(2, 3),
                  index=pd.MultiIndex.from_tuples([(0,'y'), (1, 'z')], names=['lvl0', 'lvl1']),
                  columns=list('abc'))
df

>>>                 a           b           c
>>> lvl0    lvl1            
>>>    0       y    -0.871125   0.001773     0.618647
>>>    1       z     1.001547   1.132322    -0.215681
with pd.HDFStore('test.h5') as store:
    store.put('df', df, format='t')
    store.select('df', columns=['index'])

>>> lvl0    lvl1
>>>    0       y
>>>    1       z

It works but seems not being documented.



来源:https://stackoverflow.com/questions/56403074/how-to-retrieve-pandas-df-multiindex-from-hdfstore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!