我必须从一个大文件中计算数据。文件有大约 100000 行和 3 列。下面的程序适用于小测试文件,但是当尝试使用大文件运行时,即使显示一个结果也需要很长时间。任何加快大数据文件加载和计算的建议。
代码:小测试文件计算完美,输入格式如下
from collections import defaultdict
paircount = defaultdict(int)
pairtime = defaultdict(float)
pairper = defaultdict(float)
#get number of pair occrences and total time
with open('input.txt', 'r') as f:
with open('output.txt', 'w') as o:
numline = 0
for line in f:
numline += 1
line = line.split()
pair = line[0], line[1]
paircount[pair] += 1
pairtime[pair] += float(line[2])
pairper = dict((pair, c * 100.0 / numline) for (pair, c) in paircount.iteritems())
for pair, c in paircount.iteritems():
#print pair[0], pair[1], c, pairper[pair], pairtime[pair]
o.write("%s, %s, %s, %s, %s\n" % (pair[0], pair[1], c, pairper[pair], pairtime[pair]))
输入文件:
5372 2684 460.0
1885 1158 351.0
1349 1174 6375.0
1980 1174 650.0
1980 1349 650.0
4821 2684 469.0
4821 937 459.0
2684 937 318.0
1980 606 390.0
1349 606 750.0
1174 606 750.0