Python 检查NumPy数组是否包含其他数组
在Python2.7中使用NumPy,我想创建一个nx2数组Python 检查NumPy数组是否包含其他数组,python,numpy,Python,Numpy,在Python2.7中使用NumPy,我想创建一个nx2数组y。然后,我想检查该数组是否在其任何行中包含特定的1×2数组z 这是我到目前为止尝试过的,在这种情况下,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 a
y
。然后,我想检查该数组是否在其任何行中包含特定的1×2数组z
这是我到目前为止尝试过的,在这种情况下,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'
但是,这给了我以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我做错了什么?您可以简单地使用
任意((z==x).all()表示y中的x)
。不过,我不知道它是否最快。你可以做(y==z)。all(1)。any()
更详细地说,numpy将使用一种称为“广播”的方法,在更高的维度上自动进行元素间的比较。因此,如果y
是您的n-by-2数组,而z
是您的1-by-2数组,y==z
将逐元素比较y
的每一行。然后您可以使用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
这比基于循环或生成器的方法快得多,因为它将操作矢量化。这将非常缓慢,因为它不会矢量化代码。我尝试了
n=10000
,这种方法比矢量化方法慢140多倍。是的,我实际上已经对你的答案投了赞成票,并指出我对我的速度有疑问。尽管如此,OP对速度没有明确的要求,所以我认为我不应该删除我的答案;但我认为你的应该是被标记为已接受的。