我猜这是一个简单的修复方法,但我遇到了一个问题,即使用 to_csv() 函数将 pandas 数据帧保存到 csv 文件需要将近一个小时。我将 anaconda python 2.7.12 与 pandas (0.19.1) 一起使用。
import os
import glob
import pandas as pd
src_files = glob.glob(os.path.join('/my/path', "*.csv.gz"))
# 1 - Takes 2 min to read 20m records from 30 files
for file_ in sorted(src_files):
stage = pd.DataFrame()
iter_csv = pd.read_csv(file_
, sep=','
, index_col=False
, header=0
, low_memory=False
, iterator=True
, chunksize=100000
, compression='gzip'
, memory_map=True
, encoding='utf-8')
df = pd.concat([chunk for chunk in iter_csv])
stage = stage.append(df, ignore_index=True)
# 2 - Takes 55 min to write 20m records from one dataframe
stage.to_csv('output.csv'
, sep='|'
, header=True
, index=False
, chunksize=100000
, encoding='utf-8')
del stage
我已经确认硬件和内存都在工作,但这些是相当宽的表格(约 100 列),大部分是数字(十进制)数据。
谢谢,
最佳答案
添加我的小见识,因为“gzip”替代方案对我不起作用 - 尝试使用 to_hdf 方法。这大大减少了写入时间! (对于 100MB 的文件不到一秒 - CSV 选项在 30-55 秒之间执行此操作)
stage.to_hdf(r'path/file.h5', key='stage', mode='w')
关于python - Pandas to_csv() 保存大数据帧速度慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40660331/