【问题标题】:Iterator and chunksize in HDFStore.select: "Memory error"HDFStore.select 中的迭代器和块大小:“内存错误”
【发布时间】:2017-12-01 00:46:10
【问题描述】:

据我了解,HDFStore.select 用于从大型数据集中进行选择的工具。但是,当尝试使用 chunksizeiterator=True 循环块时,一旦底层数据集足够大,迭代器本身就会变成一个非常大的对象,我不明白 为什么 迭代器对象很大,它包含什么样的信息,它必须变得如此之大。

我有一个非常大的 HDFStore 结构(70 亿行,420 GB 磁盘),我想按块进行迭代:

iterator = HDFStore.select('df', iterator=True, chunksize=chunksize)

for i, chunk in enumerate(iterator):
    # some code to apply to each chunk

当我为一个相对较小的文件运行此代码时 - 一切正常。 但是,当我尝试将其应用于 70 亿行数据库时,在计算迭代器时会得到 Memory Error。我有 32 GB 内存。

我想要一个生成器来在旅途中创建块,它不会在 RAM 中存储太多,例如:

iteratorGenerator = lambda: HDFStore.select('df', iterator=True, chunksize=chunksize)

for i, chunk in enumerate(iteratorGenerator):
    # some code to apply to each chunk

但是iteratorGenerator 是不可迭代的,所以这也不起作用。

我可能会在 startstop 行上循环 HDFStore.select,但我认为应该有一种更优雅的迭代方式。

【问题讨论】:

    标签: python pandas memory iterator hdfstore


    【解决方案1】:

    我对(仅)30GB 的文件也有同样的问题,显然你可以通过强制垃圾收集器完成它的工作来解决它......收集! :P PS:你也不需要 lambda,select 调用将返回一个迭代器,只需循环它,就像你在第一个代码块中所做的那样。

    with pd.HDFStore(file_path, mode='a') as store:
        # All you need is the chunksize
        # not the iterator=True
        iterator = store.select('df', chunksize=chunksize)
    
        for i, chunk in enumerate(iterator):
    
            # some code to apply to each chunk
    
            # magic line, that solved my memory problem
            # You also need "import gc" for this
            gc.collect()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 2020-09-24
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多