NumPy:比较两个数组中的元素 [英] NumPy: Comparing Elements in Two Arrays

查看:876
本文介绍了NumPy:比较两个数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人遇到过这个问题吗?假设您有两个类似以下的数组

Anyone ever come up to this problem? Let's say you have two arrays like the following

a = array([1,2,3,4,5,6])
b = array([1,4,5])

有没有一种方法可以比较b中a中的哪些元素?例如,

Is there a way to compare what elements in a exist in b? For example,

c = a == b # Wishful example here
print c
array([1,4,5])
# Or even better
array([True, False, False, True, True, False])

我正在尝试避免循环,因为要花数百万个元素才能解决问题.有任何想法吗?

I'm trying to avoid loops as it would take ages with millions of elements. Any ideas?

欢呼

推荐答案

实际上,有一个比以下任何一种解决方案都更简单的解决方案:

Actually, there's an even simpler solution than any of these:

import numpy as np

a = array([1,2,3,4,5,6])
b = array([1,4,5])

c = np.in1d(a,b)

然后得到的c为:

array([ True, False, False,  True,  True, False], dtype=bool)

这篇关于NumPy:比较两个数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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