检查NumPy数组是否包含另一个数组

Kar*_*rus 4 python numpy

使用NumPy和Python 2.7,我想创建一个n-by-2数组y.然后,我想检查此数组是否z在其任何行中包含特定的1 x 2数组.

这是我到目前为止所尝试的,在这种情况下,n = 1:

x = np.array([1, 2]) # Create a 1-by-2 array
y = [x] # Create an n-by-2 array (n = 1), and assign the first row to x
z = np.array([1, 2]) # Create another 1-by-2 array
if z in y: # Check if y contains the row z
    print 'yes it is'
Run Code Online (Sandbox Code Playgroud)

但是,这给了我以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

P. *_*eri 6

你可以简单地使用any((z == x).all() for x in y).不过,我不知道它是否是最快的.


The*_*Cat 6

你可以做的(y == z).all(1).any()

为了更详细一点,numpy将使用称为“广播”的东西自动在更高维度上进行逐元素比较。因此,如果y是n-by-2数组,并且z是1-by-2数组,y == z则会将的每一行yzelement-by-element进行比较。然后,您可以使用all(axis=1)来获取所有元素都匹配的行,并any()找出是否匹配。

所以这里是实践中:

>>> y1 = np.array([[1, 2], [1, 3], [1, 2], [2, 2]])
>>> y2 = np.array([[100, 200], [100,300], [100, 200], [200, 200]])
>>> z = np.array([1, 2])
>>>
>>> (y1 == z).all(1).any()
True
>>> (y2 == z).all(1).any()
False
Run Code Online (Sandbox Code Playgroud)

这比执行基于循环或基于生成器的方法要快得多,因为它可以矢量化操作。