找到numpy数组中的唯一点

Ben*_*min 9 python numpy

什么是在numpy数组中找到唯一x,y点(删除重复项)的更快方法,如:

points = numpy.random.randint(0, 5, (10,2))
Run Code Online (Sandbox Code Playgroud)

我想过将点转换为复数然后检查唯一,但这似乎相当复杂:

b = numpy.unique(points[:,0] + 1j * points[:,1])
points = numpy.column_stack((b.real, b.imag))
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 8

我会这样做:

numpy.array(list(set(tuple(p) for p in points)))

对于最常见情况下的快速解决方案,也许这个方法会让您感兴趣:http: //code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/


unu*_*tbu 7

我想你在这里有个好主意.想想用于表示数据的底层内存块points.我们告诉numpy将该块视为表示具有dtype int32(32位整数)的形状(10,2)的数组,但是告诉numpy将同一块内存视为表示形状数组(10)几乎是无成本的. ,)与dtype c8(64位复杂).

所以唯一真正的成本是打电话np.unique,接下来是另一个几乎无成本的电话viewreshape:

import numpy as np
np.random.seed(1)
points = np.random.randint(0, 5, (10,2))
print(points)
print(len(points))
Run Code Online (Sandbox Code Playgroud)

产量

[[3 4]
 [0 1]
 [3 0]
 [0 1]
 [4 4]
 [1 2]
 [4 2]
 [4 3]
 [4 2]
 [4 2]]
10
Run Code Online (Sandbox Code Playgroud)

cpoints = points.view('c8')
cpoints = np.unique(cpoints)
points = cpoints.view('i4').reshape((-1,2))
print(points)
print(len(points))
Run Code Online (Sandbox Code Playgroud)

产量

[[0 1]
 [1 2]
 [3 0]
 [3 4]
 [4 2]
 [4 3]
 [4 4]]
7
Run Code Online (Sandbox Code Playgroud)

如果你不需要对结果进行排序,那么wim的方法会更快(你可能想考虑接受他的答案......)

import numpy as np
np.random.seed(1)
N=10000
points = np.random.randint(0, 5, (N,2))

def using_unique():
    cpoints = points.view('c8')
    cpoints = np.unique(cpoints)
    return cpoints.view('i4').reshape((-1,2))

def using_set():
    return np.vstack([np.array(u) for u in set([tuple(p) for p in points])])
Run Code Online (Sandbox Code Playgroud)

产生这些基准:

% python -mtimeit -s'import test' 'test.using_set()'
100 loops, best of 3: 18.3 msec per loop
% python -mtimeit -s'import test' 'test.using_unique()'
10 loops, best of 3: 40.6 msec per loop
Run Code Online (Sandbox Code Playgroud)

  • np.unique对结果进行排序.您是否正在寻找一种方法来保持其余元素的有序性? (2认同)