【问题标题】:Get last row in pandas HDF5 query获取 pandas HDF5 查询中的最后一行
【发布时间】:2015-08-11 11:52:43
【问题描述】:

我正在尝试获取存储在 HDF5 中的 pandas 数据帧最后一行的索引无需将整个数据集或索引拉入内存。我正在寻找这样的东西:

from pandas import HDFStore

store = HDFStore('file.h5')

last_index = store.select('dataset', where='index == -1').index

除了我的情况,最后一个索引不是-1,而是Timestamp

【问题讨论】:

    标签: python pandas hdf5


    【解决方案1】:

    最后一个索引应该是

    last_index  = store['dataset'].index[-1]
    

    【讨论】:

    • 编辑了我的帖子,我需要一些不需要将整个数据集(或索引列)加载到内存中的东西
    • 明白,我会直接看 pytables 而不是 pandas。
    【解决方案2】:

    使用类似于位置索引器的 start=stop= 参数

    In [8]: df = DataFrame({'A' : np.random.randn(10000)},index=pd.date_range('20130101',periods=10000,freq='s'))
    
    In [9]: store = pd.HDFStore('test.h5',mode='w')
    
    In [10]: store.append('df',df)
    
    In [11]: nrows = store.get_storer('df').nrows
    
    In [12]: nrows
    Out[12]: 10000
    
    In [13]: store.select('df',start=nrows-1,stop=nrows)
    Out[13]: 
                                A
    2013-01-01 02:46:39 -0.890721
    
    In [15]: df.iloc[[-1]]
    Out[15]: 
                                A
    2013-01-01 02:46:39 -0.890721
    

    【讨论】:

      【解决方案3】:

      我遇到了这个问题,并且接受的答案似乎要获得最后一行(这应该很简单)需要做很多工作。通过一些整理,我能够找到一些(对我来说)感觉更简洁的东西

      设置数据

      In [8]: df = DataFrame({'A' : np.random.randn(10000)},
                              index=pd.date_range('20130101',
                              periods=10000,freq='s'))
      
      In [9]: store = pd.HDFStore('test.h5',mode='w')
      
      In [10]: store.append('df',df)
      

      事实上,可以使用以下语法提取最后一行(并确定索引):

      拉最后一行(使用start=-1

      In [11]: store.select('df',start=-1)
                                  A
      2013-01-01 02:46:39 -0.890721
      
      In [15]: df.iloc[[-1]]
      Out[15]: 
                                  A
      2013-01-01 02:46:39 -0.890721
      

      磁盘读取

      我喜欢这种形式的数据收集的另一个原因是可以使用相同的语法来读取“磁盘上”文件,特别是使用pd.read_hdf

      In [16]: s = "path/to/hdfstore/above"
      In [17]: pd.read_hdf(s, start=-1)
      Out[15]: 
                                  A
      2013-01-01 02:46:39 -0.890721
      

      这很有用,因为在处理 HDFStore 时需要使用 try, except, finally 完成大量工作,并且利用磁盘读取方法绕过了软件工程阶段的这些额外要求。

      【讨论】:

        猜你喜欢
        • 2014-07-14
        • 1970-01-01
        • 2015-12-01
        • 2017-03-12
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        相关资源
        最近更新 更多