我有大量的数据帧通过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
?即使选择最后一条记录而不为尾部拉出整个数据帧,也可能会极大地加快速度。这是如何做到的呢?
发布于 2014-10-14 17:05:20
使用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的问题
https://stackoverflow.com/questions/26372538
复制