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

编程入门 行业动态 更新时间:2024-10-12 03:24:45
本文介绍了检查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数组是否包含另一个数组

本文发布于:2023-11-29 14:07:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   NumPy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!