如何获取属于所有numpy数组的项目?

时间:2013-07-20 19:58:07

标签: python arrays numpy indexing compare

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

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比纯循环更快的方式首先与其他所有进行比较?一些阵列的联合或一些智能子索引?

2 个答案:

答案 0 :(得分:3)

您可以使用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

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

答案 1 :(得分:2)

如果每个列表都是唯一的,您可以尝试:

>>> total=np.concatenate((a,b,c))
>>> np.where(np.bincount(total)>2)
(array([1, 5]),)

#Might be faster to do this.
>>>bins=np.bincount(total)
>>>np.arange(bins.shape[0])[bins>2]
array([1, 5])

如果这些数组很大:

>>> tmp=np.concatenate((np.unique(a),np.unique(b),np.unique(c)))
>>> tmp
array([ 1,  2,  5,  6, 12,  1,  3,  5,  7,  8, 14, 19,  1,  2,  5,  6,  9,
       22])

>>> ulist,uindices=np.unique(tmp,return_inverse=True)
>>> ulist
array([ 1,  2,  3,  5,  6,  7,  8,  9, 12, 14, 19, 22])
>>> uindices
array([ 0,  1,  3,  4,  8,  0,  2,  3,  5,  6,  9, 10,  0,  1,  3,  4,  7,
       11])

>>> np.bincount(uindices)
array([3, 2, 1, 3, 2, 1, 1, 1, 1, 1, 1, 1])
>>> ulist[np.bincount(uindices)>2]
array([1, 5])