python - 处理 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
?或者也许熊猫是这项工作的错误工具?
解决方案
推荐阅读
- c# - 错误 401 未经授权即使通过身份验证也无法访问我的主页
- java - JMeter 是否适用于 OpenJDK 13?
- sql - PostgreSQL json 提取
- html - 在 routerLinkActive="active" 上更改按钮内子垫图标的颜色
- mongodb - MongoDB聚合 - 将字符串数组减少为对象,键和值作为数组中字符串的出现次数
- c++ - 您可以在 C++ 的 for 循环中使用 2 种不同类型的变量吗?
- scala - 使用 Alpakka S3 连接器的多个下载请求
- css - 在css网格中同步切换列
- dart - Dart:实例无法访问静态字段?
- go - 停止阻塞的 goroutine