如果是带有简单索引的DataFrame,则可以从HDFStore中检索索引,如下所示:
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
如docs中所述。
但是如果使用MultiIndex,这种技巧就行不通了:
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_column('df', 'index')
>>> 0 0
>>> 1 1
>>> Name: index, dtype: int64
如何检索正确的DataFrame MultiIndex?
答案 0 :(得分:0)
可以将select
与指定的columns=['index']
参数一起使用:
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
它可以工作,但似乎不是documented。