如何获取属于所有numpy数组的项目? [英] how to get items that belongs to all numpy arrays?

查看:166
本文介绍了如何获取属于所有numpy数组的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些模拟numpy.in1d()函数,我的任务是拥有超过2个数组的项目列表。例如,我有3个数组:

I need some analogue to numpy.in1d() function, my task is to have list of items, that more than 2 arrays have. For example i have 3 arrays:

a = np.array((1,2,5,6,12))
b = np.array((1,3,7,8,5,14,19))
c = np.array((2,6,9,5,1,22))

结果应为[1,5]

使用np.in1d比纯循环更快的方式首先与所有其余的进行比较?一些数组联合或一些智能子索引?

Any faster way than pure cycle using np.in1d to compare first with all the rest? Some unions of arrays or some smart subindexing?

推荐答案

你可以使用 np.intersect1d 。例如:

In [15]: np.intersect1d(a, np.intersect1d(b, c))
Out[15]: array([1, 5])

reduce

In [16]: reduce(np.intersect1d, (a, b, c))
Out[16]: array([1, 5])

如果你知道每个数组中的元素是唯一的,使用参数 assume_unique = True

If you know the elements within each array are unique, use the argument assume_unique=True:

In [21]: reduce(lambda x, y: np.intersect1d(x, y, assume_unique=True), (a, b, c))
Out[21]: array([1, 5])

这篇关于如何获取属于所有numpy数组的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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