Pandas HDFStore - 从多个表中获取最后记录

时间:2014-10-15 00:21:32

标签: python pandas hdfstore hdf

我有大量的数据帧通过Pandas导出到一系列HDFStore文件中。我需要能够根据需要为每个数据帧快速提取最新记录。

设置:

<class 'pandas.io.pytables.HDFStore'>
File path: /data/storage_X100.hdf
/X1                   frame_table  (typ->appendable,nrows->2652,ncols->1,indexers->[index])
/XX                   frame_table  (typ->appendable,nrows->2652,ncols->3,indexers->[index])
/Y1                   frame_table  (typ->appendable,nrows->2652,ncols->2,indexers->[index])
/YY                   frame_table  (typ->appendable,nrows->2652,ncols->3,indexers->[index])

我在每个HDF文件中存储大约100个数据帧,并且有大约5000个文件可供运行。 HDFStore中的每个数据帧都使用DateTimeIndex索引。

对于单个文件,我目前正在遍历HDFStore.keys(),然后使用tail(1)查询数据框,如下所示:

store = pandas.HDFStore(filename)
lastrecs = {}
for key in store.keys():
   last = store[key].tail(1)
   lastrecs[key] = last

是否有更好的方法可以使用HDFStore.select_as_multiple?即使选择最后一条记录而不拉动整个数据帧尾部也可能会大大加快速度。怎么办呢?

1 个答案:

答案 0 :(得分:2)

使用start和/或stop指定行范围。你仍然需要遍历键,但这只会选择表的最后一行,所以应该非常快。

In [1]: df = DataFrame(np.random.randn(10,5))

In [2]: df.to_hdf('test.h5','df',mode='w',format='table')

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

In [4]: store
Out[4]: 
<class 'pandas.io.pytables.HDFStore'>
File path: test.h5
/df            frame_table  (typ->appendable,nrows->10,ncols->5,indexers->[index])

In [5]: nrows = store.get_storer('df').nrows

In [6]: nrows
Out[6]: 10

In [7]: store.select('df',start=nrows-1,stop=nrows)
Out[7]: 
          0        1         2         3         4
9  0.221869 -0.47866  1.456073  0.093266 -0.456778

In [8]: store.close()

这是一个使用nrows(用于不同目的)here

的问题
相关问题