问题描述
当使用pandas读取大文本文件时,会由于内存不足产生MemoryError异常,可以设置分块读取的方式来解决。
代码实现
import pandas as pd
# 由于数据量较大,一次性读入可能造成内存错误(Memmory Error),因而使用pandas的分块读取
def read_from_local(file_name, chunk_size=500000):
reader = pd.read_csv(file_name, header=0, iterator=True, encoding="utf-8")
chunks = []
loop = True
while loop:
try:
chunk = reader.get_chunk(chunk_size)
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped!")
# 将块拼接为pandas dataFrame格式
df_ac = pd.concat(chunks, ignore_index=True)
return df_ac
转载自 https://blog.csdn.net/qq_41689620/article/details/95106239
网友评论