【问题标题】:Pandas HDFStore - Get Last Record from Multiple TablesPandas HDFStore - 从多个表中获取最后一条记录
【发布时间】:2014-12-09 22:32:32
【问题描述】:

我有大量的数据帧通过 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?即使选择最后一条记录而不将整个数据框拉到尾部也可能会大大加快速度。如何做到这一点?

【问题讨论】:

    标签: python pandas hdfstore hdf


    【解决方案1】:

    使用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

    【讨论】:

      猜你喜欢
      • 2022-10-01
      • 2012-02-13
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      相关资源
      最近更新 更多