1

我需要一些类似于 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 与其他所有方法进行比较的纯循环更快的方法?一些数组联合或一些智能子索引?

4

2 回答 2

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])
于 2013-07-20T21:23:32.013 回答
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])
于 2013-07-20T20:10:02.233 回答