python – 使用HDF5和Pandas通过Chunking读取数据
作者:互联网
当在内存中查询数据形成CSV的子集时,我总是这样做:
df = pd.read_csv('data.csv', chunksize=10**3)
chunk1 = df.get_chunk()
chunk1 = chunk1[chunk1['Col1'] > someval]
for chunk in df:
chunk1.append(chunk[chunk['Col1'] >someval])
我最近开始使用HDF5,因为TableIterator对象没有get_chunk()方法或者接受next(),所以无法做到这一点.
df = pd.read_hdf('data.h5', chunksize=10**3)
df.get_chunk()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-19-xxxxxxxx> in <module>()
----> 1 df.get_chunk()
AttributeError: 'TableIterator' object has no attribute 'get_chunk'
任何解决方法的想法? (我知道我可以使用pandas从磁盘上的hdf5查询,但为了这个目的,我想尝试这种方式)
解决方法:
在这种情况下使用HDF索引确实很有意义,因为它更有效.
这是一个小型演示:
生成测试DataFrame(10M行,3列):
In [1]: df = pd.DataFrame(np.random.randint(0,10**7,(10**7,3)),columns=list('abc'))
In [2]: df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000000 entries, 0 to 9999999
Data columns (total 3 columns):
a int32
b int32
c int32
dtypes: int32(3)
memory usage: 114.4 MB
In [3]: df.shape
Out[3]: (10000000, 3)
将DF保存到HDF文件.确保列a已编入索引(data_columns = [‘a’,…]或data_columns = True – 以索引所有列)
fn = r'c:/tmp/test.h5'
store = pd.HDFStore(fn)
store.append('test', df, data_columns=['a'])
store.close()
del df
从HDF文件中读取测试:
fn = r'c:/tmp/test.h5'
chunksize = 10**6
someval = 100
定时:
读取块中的HDF并将过滤后的块连接到生成的DF中
In [18]: %%timeit
...: df = pd.DataFrame()
...: for chunk in pd.read_hdf(fn, 'test', chunksize=chunksize):
...: df = pd.concat([df, chunk.ix[chunk.a < someval]], ignore_index=True)
...:
1 loop, best of 3: 2min 22s per loop
读取块中的HDF(有条件地 – 通过HDF索引过滤数据)并将块连接到生成的DF中:
In [19]: %%timeit
...: df = pd.DataFrame()
...: for chunk in pd.read_hdf(fn, 'test', chunksize=chunksize, where='a < someval'):
...: df = pd.concat([df, chunk], ignore_index=True)
...:
10 loops, best of 3: 79.1 ms per loop
结论:通过索引(使用where =< terms>)搜索HDF比读取所有内容和在内存中过滤快1795倍:
In [20]: (2*60+22)*1000/79.1
Out[20]: 1795.19595448799
标签:python,pandas,python-2-7,hdf5,pytables 来源: https://codeday.me/bug/20190722/1502168.html