numpy:如何检查数组是否包含某些数字? [英] Numpy: How to check if array contains certain numbers?

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

问题描述

例如:我有a = np.array([123, 412, 444])b = np.array([123, 321])

我想知道a是否包含b中的所有元素.为此有一个简单的操作吗?在这种情况下,那是不正确的.

I want to know if a contains all the elements in b. Is there a simple operation for this? In this case that would not be true.

推荐答案

您可以使用设置差异来确定要查找的内容. Numpy具有内置函数,称为 numpy.setdiff1d(ar1,ar2 ):

You can use set difference to determine what you are looking for. Numpy has a built-in function called numpy.setdiff1d(ar1, ar2):

返回ar1中不在ar2中的排序后的唯一值.

Return the sorted, unique values in ar1 that are not in ar2.

您的案例示例:

>>> a = np.array([123, 412, 444])
>>> b = np.array([123, 321])
>>> diff = np.setdiff1d(b, a)
>>> print diff
array([321])
>>> if diff.size:
>>>    print "Not passed"

因此,对于您的情况,您将做一个集合差,即从b中减去a并获得一个数组,其中b中的元素不在a中.然后,您可以检查是否为空.如您所见,输出为312,这是a中存在的条目,而在b中却没有.它的长度现在大于零,因此b中的某些元素在a中不存在.

So for your case, you would do a set difference you would subtract a from b and obtain an array with elements in b which are not in a. Then you can check if that was empty or not. As you can see, the output is 312, which is an entry present in a but not in b; the length of it is now larger then zero, therefore there were elements in b which were not present in a.

这篇关于numpy:如何检查数组是否包含某些数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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