从h5文件中读取n行

时间:2015-03-16 04:20:42

标签: python pandas

我想从h5文件中只读取10个

df = pd.read_hdf('data.h5', 'cleanuserbase', start=0, stop=10)

但这不起作用,因为它会读取所有行。

2 个答案:

答案 0 :(得分:1)

仅当您的对象是表格格式(而不是fixed format)时才有效。

In [11]: df = pd.DataFrame(np.random.randn(100, 2))

In [12]: store = pd.HDFStore('store.h5')

In [13]: df.to_hdf("store.h5", "df", format="table")

In [14]: store.select("df", "index < 2")
Out[14]:
          0         1
0 -0.245982 -1.047534
1 -0.633943 -1.218812

In [15]: pd.read_hdf("store.h5", "df", start=0, stop=2)  # works if non-integer index
Out[15]:
          0         1
0 -0.245982 -1.047534
1 -0.633943 -1.218812

请参阅文档中的table format


如果您的表格是固定格式,则只能整体阅读(但可能是this should raise):

In [21]: df.to_hdf("store.h5", "fixed_df", format="fixed")

In [22]: pd.read_hdf("store.h5", "fixed_df", start=0, stop=2)
Out[22]:
           0         1
0   2.532604 -0.084852
1   0.735833 -1.100600
2  -0.415245 -2.050627
3  -0.915045 -0.638667
...  # and all the other rows

答案 1 :(得分:1)

这不适用于fixed商店ATM(但适用于table商店,请参阅Andy的回答),请参阅未解决的问题here

也就是说,商店本身确实支持索引。它只是没有建成。这是在窥视内部。

In [35]: df = DataFrame(np.random.randn(10,2),columns=list('ab'))

In [36]: store = pd.HDFStore('test.h5',mode='w')

In [37]: store.put('df',df)

In [38]: store
Out[38]: 
<class 'pandas.io.pytables.HDFStore'>
File path: test.h5
/df            frame        (shape->[10,2])

In [39]: mask = slice(4,10)

In [40]: s = store.get_storer('df').storable

In [41]: DataFrame(s.block0_values[mask],index=s.axis1[mask],columns=s.axis0)
Out[41]: 
axis0         a         b
4     -1.347325 -0.936605
5     -0.342814 -0.452055
6      0.951228  0.160918
7     -0.096133  0.816032
8     -0.731431  1.190047
9     -1.050826  0.348107

In [42]: store.close()

我认为这可能会引发NotImplementedError,直到此问题得到解决。

相关问题