【发布时间】:2017-08-09 20:16:32
【问题描述】:
我正在尝试显着加快以下代码的速度,但无济于事。该代码采用二维数组并删除与数组中的其他行相比过于相似的数组行。请参阅下面的代码和 cmets。
as0 = a.shape[0]
for i in range(as0):
a2s0 = a.shape[0] # shape may change after each iteration
if i > (a2s0 - 1):
break
# takes the difference between all rows in array by iterating over each
# row. Then sums the absolutes. The condition finally gives a boolean
# array output - similarity condition of 0.01
t = np.sum(np.absolute(a[i,:] - a), axis=1)<0.01
# Retains the indices that are too similar and then deletes the
# necessary row
inddel = np.where(t)[0]
inddel = [k for k in inddel if k != i]
a = np.delete(a, inddel, 0)
我想知道矢量化是否可行,但我不太熟悉。任何帮助将不胜感激。
编辑:
if i >= (a2s0 - 1): # Added equality sign
break
# Now this only calculates over rows that have not been compared.
t = np.sum(np.absolute(a[i,:] - a[np.arange(i+1,a2s0),:]), axis=1)>0.01
t = np.concatenate((np.ones(i+1,dtype=bool), t))
a = a[t, :]
【问题讨论】:
-
假设我们有行号:
6,10,12“相似”彼此。那么,是否可以删除前两行并保留最后一行,即12? -
是的。删除哪些索引并不重要。只要唯一的行仍然存在。
标签: python performance numpy vectorization