检查NumPy数组是否包含另一个数组 [英] Checking if a NumPy array contains another array

查看:746
本文介绍了检查NumPy数组是否包含另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using NumPy with Python 2.7, I want to create an n-by-2 array y. Then, I want to check whether this array contains a particular 1-by-2 array z in any of its rows.

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

Here's what I have tried so far, and in this case, 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'

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

However, this gives me the following error:

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

我在做什么错了?

推荐答案

您可以执行(y == z).all(1).any().

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

To go into a bit more detail, numpy will element-by-element comparisons across higher dimensions automatically using something called "broadcasting". So if y is your n-by-2 array, and z is your 1-by-2 array, y == z will compare each row of y with z element-by-element. Then you can just use all(axis=1) to get the rows where all elements match, and any() to find out if any match.

这是实际的情况:

>>> 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

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

This is considerably faster than doing a loop or generator-based approach since it vectorizes the operation.

这篇关于检查NumPy数组是否包含另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆