获取pandas HDF5查询的最后一行

问题描述 投票:3回答:3

我试图得到存储在HDF5中的pandas数据帧的最后一行的索引,而不必将整个数据集或索引拉入内存。我正在寻找这样的东西:

from pandas import HDFStore

store = HDFStore('file.h5')

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

除了在我的情况下,最后一个指数不是-1而是Timestamp

python pandas hdf5
3个回答
6
投票

使用与位置索引器类似的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

0
投票

最后的索引应该是

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

0
投票

我遇到了这个问题,接受的答案似乎是要完成最后一行(这应该是直截了当的)。通过一些改变,我能够找到一些感觉更简洁的东西(对我来说)

设置数据

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

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

© www.soinside.com 2019 - 2024. All rights reserved.