我需要找到重复的2D numpy的阵列。因此,我想要一个与输入相同长度的列表,指向相应值的第一次出现。例如,数组[[1,0,0],[1,0,0],[2,3,4]]具有两个相等的元素0和1.该方法应返回[0,0,2](请参阅下面的代码中的例子)。 以下代码正在运行,但对于大型阵列来说速度很慢。蟒蛇numpy的加快2D重复的搜索
import numpy as np
def duplicates(ar):
"""
Args:
ar (array_like): array
Returns:
list of int: int is pointing to first occurence of unique value
"""
# duplicates array:
dup = np.full(ar.shape[0], -1, dtype=int)
for i in range(ar.shape[0]):
if dup[i] != -1:
# i is already found to be a
continue
else:
dup[i] = i
for j in range(i + 1, ar.shape[0]):
if (ar[i] == ar[j]).all():
dup[j] = i
return dup
if __name__ == '__main__':
n = 100
# shortest extreme for n points
a1 = np.array([[0, 1, 2]] * n)
assert (duplicates(a1) == np.full(n, 0)).all(), True
# longest extreme for n points
a2 = np.linspace(0, 1, n * 3).reshape((n, 3))
assert (duplicates(a2) == np.arange(0, n)).all(), True
# test case
a3 = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
assert (duplicates(a3) == [0, 0, 2]).all(), True
任何想法如何加快过程(例如避免第二个循环)或替代实现? 干杯
矢量化方法似乎有特殊情况的问题(见我的答复编辑) –
@DanielBöckenhoff烨是一个很小的错误。应该是'.any'而不是'.all'。刚刚修好。这不应该改变时机。 – Divakar