簡體   English   中英

從h5文件讀取n行

[英]Read n rows from an h5 file

我只想從h5文件中讀取10

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

但這是行不通的,因為它會讀取所有行。

僅當您的對象是表格式(而不是固定格式 )時,此方法才有效。

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

請參閱文檔中的表格格式


如果您的表格是固定格式,則只能全部讀取(但是應該會引起這個問題 ):

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

這不適用於fixed存儲的ATM(但適用於table存儲,請參見Andy的答案),請參見此處的未解決問題

也就是說,商店本身確實支持索引編制。 它只是沒有建立。 這正在窺探內部。

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直到解決此問題為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM