首页 > 解决方案 > 处理 Pandas 中的 MemoryError

问题描述

我正在尝试读取 349 个 csv 文件,它们都具有相同的列和 c。总共 15gb,并将它们组合成 1 个数据帧。但是,我不断收到MemoryError,因此尝试每 10 个文件使用 10-20 秒睡眠。我下面的代码设法将它们读入 dfs 列表,尽管有时它会崩溃。

import glob
import os
import time
import pandas as pd 

path = r"C:\path\*\certificates.csv"
files = []
for filename in glob.iglob(path, recursive=True):
    files.append(filename) 
    #print(filename)

dfs = []
sleep_for = 20
counter = 0
for file in files: 
    counter += 1 
    if counter % 10 == 0:
        time.sleep(sleep_for)
        print("\nSleeping for " + str(sleep_for) + " seconds.\nProceeding to append df " + str(counter))
        df = pd.read_csv(file)
        df = df[keep_cols] # A list of cols to keep - same in every file
        dfs.append(df)        
    else:    
        df = pd.read_csv(file)
        df = df[domestic_keep_cols]
        dfs.append(df)
        print('Appending df ' + str(counter))
df_combined = pd.concat(dfs)

但是,当我尝试pd.concat使用 dfs 列表时,我得到一个MemoryError. 我试图通过一次附加 10 个 dfs 来解决这个问题:

lower_limit = 0
upper_limit = 10
counter = 0

while counter < len(dfs):   
    counter += 1 
    target_dfs = dfs[lower_limit:upper_limit]
    if counter % 10 == 0:
        lower_limit += 10
        upper_limit += 10
        target_dfs = dfs[lower_limit:upper_limit]
        for each_df in target_dfs:
            df_combined = df_combined.append(each_df)
    else:
        for each_df in target_dfs:
            df_combined = df_combined.append(each_df)

但是,这也会抛出MemoryError,有没有更有效的方法来做到这一点,或者我做错了什么是抛出MemoryError?或者也许熊猫是这项工作的错误工具?

标签: pythonpython-3.xpandas

解决方案


推荐阅读