我有大量的数据帧通过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
)?即使选择最后一条记录而不拖尾整个数据帧也可能极大地加快了速度。如何才能做到这一点? 最佳答案
使用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
关于python - Pandas HDFStore-从多个表中获取最新记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26372538/