【发布时间】:2016-11-28 12:10:14
【问题描述】:
我有一个 ~50GB 的 csv 文件,我必须使用它
- 获取 CSV 列的几个子集
- 对 CSV 的每个列子集应用不同的格式字符串规范。
- 为每个具有自己的格式规范的子集输出一个新的 CSV。
我选择使用 Pandas,并有一种通用的方法来迭代一个方便的块大小(超过 50 万行)的块以生成一个 DataFrame,并将该块附加到每个输出 CSV。所以是这样的:
_chunk_size = 630100
column_mapping = {
'first_output_specification' : ['Scen', 'MS', 'Time', 'CCF2', 'ESW10'],
# ..... similar mappings for rest of output specifications
}
union_of_used_cols = ['Scen', 'MS', 'Time', 'CCF1', 'CCF2', 'VS', 'ESW 0.00397', 'ESW0.08',
'ESW0.25', 'ESW1', 'ESW 2', 'ESW3', 'ESW 5', 'ESW7', 'ESW 10', 'ESW12',
'ESW 15', 'ESW18', 'ESW 20', 'ESW22', 'ESW 25', 'ESW30', 'ESW 35',
'ESW40']
chnk_iter = pd.read_csv('my_big_csv.csv', header=0, index_col=False,
iterator=True, na_filter=False, usecols=union_of_used_cols)
cnt = 0
while cnt < 100:
chnk = chnk_iter.get_chunk(_chunk_size)
chnk.to_csv('first_output_specification', float_format='%.8f',
columns=column_mapping['first_output_specification'],
mode='a',
header=True,
index=False)
# ..... do the same thing for the rest of the output specifications
cnt += 1
我的问题是这真的很慢。每个块需要大约一分钟来生成附加到 CSV 文件,因此我正在寻找近 2 个小时来完成任务。
我尝试通过在读取 CSV 时仅使用列子集的并集以及设置 na_filter=False 来进行一些优化,但这仍然是不可接受的。
我想知道是否有更快的方法在 Python 中对 CSV 文件进行这种轻量级处理,或者通过优化或更正我的方法,或者可能只是有一个更好的工具适合这种工作Pandas... 对我(一个没有经验的 Pandas 用户)来说,这看起来和 Pandas 一样快,但我很可能弄错了。
【问题讨论】:
-
是否可以切换到数据库方法?这是一个大的 csv 文件!
-
@Jylo 我真的希望是这样,但不是。
-
chunksize是否包含您希望在每个块中拥有的行数? -
@albert 看起来瓶颈肯定是用
to_csv写入csv:简单地将输入分块到数据帧中并且对它们不做任何事情非常快,。我现在找到了。所以我不确定 PowerShell 文件拆分是否会有所不同。
标签: python file csv pandas optimization