我正在尝试使用pandas库将一个大型(大约4 4Gb) csv数据集导入到python中。当然,数据集不能一次全部放入内存中,因此我使用大小为10000的块来读取csv。在这之后,我想将所有的块合并成一个数据帧,以便执行一些计算,但我耗尽了内存(我使用的是具有16 to的台式机)。
到目前为止我的代码如下:
# Reading csv
chunks = pd.read_csv("path_to_csv", iterator=True, chunksize=1000)
# Concat the chunks
pd.concat([chunk for chunk in chunks])
pd.concat(chunks, ignore_index=True)我在StackOverflow上搜索了许多帖子,所有这些帖子都提出了其中一个解决方案。有没有办法克服这个问题?我不敢相信我不能处理一个4 gb的数据集和16 gb的内存!
更新:我还没有想出任何导入csv文件的解决方案。我绕过了这个问题,将数据导入PostgreSQL,然后查询数据库。
发布于 2017-05-10 19:59:56
我曾经在python中使用生成器处理过这种情况。我希望这会对你有所帮助:
def read_big_file_in_chunks(file_object, chunk_size=1024):
"""Reading whole big file in chunks."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
f = open('very_very_big_file.log')
for chunk in read_big_file_in_chunks(f):
process_data(chunck)https://stackoverflow.com/questions/43891473
复制相似问题