如何根据第一列的内容拆分巨大的 csv 文件? [英] How to split a huge csv file based on content of first column?
本文介绍了如何根据第一列的内容拆分巨大的 csv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我有一个 250MB 以上的巨大 csv 文件要上传
- 文件格式为
group_id、application_id、reading
,数据看起来像
1, a1, 0.11, a1, 0.21, a1, 0.41, a1, 0.31, a1, 0.01, a1, 0.92、b1、0.12, b1, 0.22, b1, 0.42, b1, 0.32, b1, 0.02, b1, 0.9.....n, x, 0.3(可以说)
- 我想根据
group_id
分割文件,所以输出应该是n个文件,其中n=group_id
输出
<块引用>文件 11, a1, 0.11, a1, 0.21, a1, 0.41, a1, 0.31, a1, 0.01, a1, 0.9
和
<块引用>File22、b1、0.12, b1, 0.22, b1, 0.42, b1, 0.32, b1, 0.02, b1, 0.9.....
和
<块引用>文件nn, x, 0.3(可以说)
我怎样才能有效地做到这一点?
解决方案
如果文件已经按group_id
排序,你可以这样做:
导入csv从 itertools 导入 groupby对于 key,groupby(csv.reader(open("foo.csv")) 中的行,拉姆达行:行[0]):以 open("%s.txt" % key, "w") 作为输出:对于行中的行:output.write(",".join(row) + "
")
- I have a 250MB+ huge csv file to upload
- file format is
group_id, application_id, reading
and data could look like
1, a1, 0.1 1, a1, 0.2 1, a1, 0.4 1, a1, 0.3 1, a1, 0.0 1, a1, 0.9 2, b1, 0.1 2, b1, 0.2 2, b1, 0.4 2, b1, 0.3 2, b1, 0.0 2, b1, 0.9 ..... n, x, 0.3(lets say)
- I want to divide the file based on
group_id
, so output should be n files wheren=group_id
Output
File 1 1, a1, 0.1 1, a1, 0.2 1, a1, 0.4 1, a1, 0.3 1, a1, 0.0 1, a1, 0.9
and
File2 2, b1, 0.1 2, b1, 0.2 2, b1, 0.4 2, b1, 0.3 2, b1, 0.0 2, b1, 0.9 .....
and
File n n, x, 0.3(lets say)
How can I do this effectively?
解决方案
If the file is already sorted by group_id
, you can do something like:
import csv
from itertools import groupby
for key, rows in groupby(csv.reader(open("foo.csv")),
lambda row: row[0]):
with open("%s.txt" % key, "w") as output:
for row in rows:
output.write(",".join(row) + "
")
这篇关于如何根据第一列的内容拆分巨大的 csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文