如何在numpy二维数组中找到与某个列表匹配的所有元素?

2024-04-26 21:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维NumPy数组,例如:

array([[1, 1, 0, 2, 2],
       [1, 1, 0, 2, 0],
       [0, 0, 0, 0, 0],
       [3, 3, 0, 4, 4],
       [3, 3, 0, 4, 4]])

我想从该数组中获取某个列表中的所有元素,例如(1,3,4)。在示例中,期望的结果是:

^{pr2}$

我知道我可以做(正如这里推荐的Numpy: find elements within range):

np.logical_or(
    np.logical_or(cc_labeled == 1, cc_labeled == 3),
    cc_labeled == 4
)

,但这仅在示例中有效。实际上,迭代使用for循环和numpy.logical\u或结果是非常慢的,因为可能值的列表是以千为单位的(numpy数组的维数大约为1000 x 1000)。在


Tags: ornumpy元素示例列表np数组find
2条回答

使用^{}

np.in1d(arr, [1,3,4]).reshape(arr.shape)

in1d,顾名思义,是在平坦数组上操作的,因此需要在操作之后进行整形。

您可以使用^{}-

A*np.in1d(A,[1,3,4]).reshape(A.shape)

另外,^{}可以用来-

^{pr2}$

您还可以使用^{}来查找这类匹配,方法是使用其可选的'side'参数,输入为left和{},并注意到对于匹配项,searchsorted将使用这两个输入输出不同的结果。因此,np.in1d(A,[1,3,4])的等价物是-

M = np.searchsorted([1,3,4],A.ravel(),'left') != \
    np.searchsorted([1,3,4],A.ravel(),'right')

因此,最终输出将是-

out = A*M.reshape(A.shape)

请注意,如果输入搜索列表未排序,则需要使用可选参数sorter,并在np.searchsorted中使用其argsort索引。

样本运行-

In [321]: A
Out[321]: 
array([[1, 1, 0, 2, 2],
       [1, 1, 0, 2, 0],
       [0, 0, 0, 0, 0],
       [3, 3, 0, 4, 4],
       [3, 3, 0, 4, 4]])

In [322]: A*np.in1d(A,[1,3,4]).reshape(A.shape)
Out[322]: 
array([[1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [3, 3, 0, 4, 4],
       [3, 3, 0, 4, 4]])

In [323]: np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)
Out[323]: 
array([[1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [3, 3, 0, 4, 4],
       [3, 3, 0, 4, 4]])

In [324]: M = np.searchsorted([1,3,4],A.ravel(),'left') != \
     ...:     np.searchsorted([1,3,4],A.ravel(),'right')
     ...: A*M.reshape(A.shape)
     ...: 
Out[324]: 
array([[1, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [3, 3, 0, 4, 4],
       [3, 3, 0, 4, 4]])

运行时测试和验证输出-

In [309]: # Inputs
     ...: A = np.random.randint(0,1000,(400,500))
     ...: lst = np.sort(np.random.randint(0,1000,(100))).tolist()
     ...: 
     ...: def func1(A,lst):                         
     ...:   return A*np.in1d(A,lst).reshape(A.shape)
     ...: 
     ...: def func2(A,lst):                         
     ...:   return np.where(np.in1d(A,lst).reshape(A.shape),A,0)
     ...: 
     ...: def func3(A,lst):                         
     ...:   mask = np.searchsorted(lst,A.ravel(),'left') != \
     ...:          np.searchsorted(lst,A.ravel(),'right')
     ...:   return A*mask.reshape(A.shape)
     ...: 

In [310]: np.allclose(func1(A,lst),func2(A,lst))
Out[310]: True

In [311]: np.allclose(func1(A,lst),func3(A,lst))
Out[311]: True

In [312]: %timeit func1(A,lst)
10 loops, best of 3: 30.9 ms per loop

In [313]: %timeit func2(A,lst)
10 loops, best of 3: 30.9 ms per loop

In [314]: %timeit func3(A,lst)
10 loops, best of 3: 28.6 ms per loop

相关问题 更多 >