我的代码需要大约两个小时来处理。瓶颈是for循环,如果 声明(请参阅代码中的注释)。 我是初学者与蟒蛇:)任何人都可以推荐一种高效的Python方法来替换嵌套和if语句?关于在我的代码中加快/ if语句的建议?
我有〜3000万行的表,每一行与(X,Y,Z)值:
20.0 11.3 7
21.0 11.3 0
22.0 11.3 3
...
我所需的输出是x,y,min(z),count(min(z))形式的表格。最后的 列是该(x,y)处最小z值的最终计数。例如:
20.0 11.3 7 7
21.0 11.3 0 10
22.0 11.3 3 1
...
这里只有大约600独特的坐标,所以输出表将被600x4。 我的代码:
import numpy as np
file = open('input.txt','r');
coordset = set()
data = np.zeros((600,4))*np.nan
irow = 0
ctr = 0
for row in file:
item = row.split()
x = float(item[0])
y = float(item[1])
z = float(item[2])
# build unique grid of coords
if ((x,y)) not in coordset:
data[irow][0] = x
data[irow][1] = y
data[irow][2] = z
irow = irow + 1 # grows up to 599
# lookup table of unique coords
coordset.add((x,y))
# BOTTLENECK. replace ifs? for?
for i in range(0, irow):
if data[i][0]==x and data[i][1]==y:
if z > data[i][2]:
continue
elif z==data[i][2]:
ctr = ctr + 1
data[i][3]=ctr
if z < data[i][2]:
data[i][2] = z
ctr = 1
data[i][3]=ctr
编辑:上供@Joowani的方法计算在1m26s。我原来的方法,相同的电脑,相同的数据文件,106m23s。 编辑2: @Ophion和@Sibster感谢您的建议,我没有足够的信用+1 +1有用的答案。
是3千万行真的很棒保存在TXT?你不应该看一些更复杂的格式来保存(并读入)你的数据吗?此外,我建议尽可能向量化(numpy),因为这会将for-loops推入numpy,这是C(因此更快) – usethedeathstar