简体   繁体   English

不同长度的numpy数组的元素比较

[英]Elementwise comparison of numpy arrays with different lengths

I want to compare the elements of two 3D numpy arrays of different lengths. 我想比较两个不同长度的3D numpy数组的元素。 The goal is, to find overlapping elements in the two arrays. 目的是在两个数组中查找重叠的元素。

All functions I found so far, rely on the two arrays being of the same lengths. 到目前为止,我发现的所有函数都依赖两个长度相同的数组。

Is there an efficient way to do compare the 2D-elements (for loops will be very inefficient, since each array has tens of thousands of elements)? 有没有一种比较2D元素的有效方法(对于循环来说,效率很低,因为每个数组都有成千上万个元素)?

Is intersect1d what you want? 您想要的是intersect1d吗? For example, if your arrays are a and b , you could simply do: 例如,如果您的数组是ab ,则可以简单地执行以下操作:

duplicates = np.intersect1d(a, b)

Here a few ways of comparing 2 1d arrays: 以下是比较2个1d数组的几种方法:

In [325]: n=np.arange(0,10)
In [326]: m=np.arange(3,9)

In [327]: np.in1d(n,m)
Out[327]: array([False, False, False,  True,  True,  True,  True,  True,  True, False], dtype=bool)

In [328]: np.in1d(m,n)
Out[328]: array([ True,  True,  True,  True,  True,  True], dtype=bool)

In [329]: n[:,None]==m[None,:]
Out[329]: 
array([[False, False, False, False, False, False],
       [False, False, False, False, False, False],
       [False, False, False, False, False, False],
       [ True, False, False, False, False, False],
       [False,  True, False, False, False, False],
       [False, False,  True, False, False, False],
       [False, False, False,  True, False, False],
       [False, False, False, False,  True, False],
       [False, False, False, False, False,  True],
       [False, False, False, False, False, False]], dtype=bool)

and farenorth s suggestion farenorth的建议

In [330]: np.intersect1d(n,m)
Out[330]: array([3, 4, 5, 6, 7, 8])

In [331]: np.where(np.in1d(n,m))
Out[331]: (array([3, 4, 5, 6, 7, 8], dtype=int64),)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM