我试图得到存储在HDF5中的pandas数据帧的最后一行的索引,而不必将整个数据集或索引拉入内存。我正在寻找这样的东西:
from pandas import HDFStore
store = HDFStore('file.h5')
last_index = store.select('dataset', where='index == -1').index
除了在我的情况下,最后一个指数不是-1
而是Timestamp
使用与位置索引器类似的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
最后的索引应该是
last_index = store['dataset'].index[-1]
我遇到了这个问题,接受的答案似乎是要完成最后一行(这应该是直截了当的)。通过一些改变,我能够找到一些感觉更简洁的东西(对我来说)
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
完成大量的工作,并且利用磁盘读取方法可以绕过软件工程阶段的额外要求。