【问题标题】:Reading Data by Chunking with HDF5 and Pandas通过 HDF5 和 Pandas 分块读取数据
【发布时间】:2017-03-13 22:27:07
【问题描述】:

当从 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 查询,但为此我想尝试这种方式)

【问题讨论】:

    标签: python python-2.7 pandas hdf5 pytables


    【解决方案1】:

    在这种情况下使用 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
    

    结论:通过索引搜索 HDF(使用 where=&lt;terms&gt;)比读取所有内容并在内存中过滤要快 1795 倍:

    In [20]: (2*60+22)*1000/79.1
    Out[20]: 1795.19595448799
    

    【讨论】:

    • 您是如何完成这项工作的?当我尝试上面的代码时,我收到如下错误:ValueError: Shape of passed values is (1, 100000), indices imply (1, 1551440685) - 我尝试了块大小、迭代器等的所有可能组合,但它总是失败......
    • @DejanLekic,您是否尝试执行我回答中的代码?你的 Pandas 版本是什么?
    • pandas 0.20.1, tables 3.4.2 ... 出现这个奇怪的错误...你的确切版本会很棒,所以我可以将我的要求固定在那些上,然后再试一次......顺便说一句,我不能在哪里使用。我需要加载所有记录,因为我正在尝试将 HDF5 文件逐表转换为 Parquet ...
    • @DejanLekic,刚刚针对 Pandas 进行了测试:0.20.1,表:3.2.2,numpy:1.12.1
    【解决方案2】:

    简单地说:

    chunk1 = pd.concat([chunk[chunk['Col1'] > someval] for chunk in df])
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 2021-02-24
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2015-08-09
      • 1970-01-01
      • 2020-07-26
      相关资源
      最近更新 更多