I have two 1D arrays and I want to find out if an element in one array occurs in another array or not.
我有两个1D数组,我想知道一个数组中的元素是否出现在另一个数组中。
For example:
import numpy as np
A = np.array([ 1, 48, 50, 78, 85, 97])
B = np.array([38, 43, 50, 62, 78, 85])
I want:
C = [2,3,4] # since 50 in second array occurs in first array at index 2,
# similarly 78 in second array occurs in first array in index 3,
# similarly for 85, it is index 4
I tried:
accuracy = np.searchsorted(A, B)
But it gives me undesirable results.
但它给我带来了不良后果。
2 个解决方案
#1
10
You could use np.where
and np.in1d
:
你可以使用np.where和np.in1d:
>>> np.where(np.in1d(A, B))[0]
array([2, 3, 4])
np.in1d(A, B)
returns a boolean array indicating whether each value of A
is found in B
. np.where
returns the indices of the True
values. (This will also work if your arrays are not sorted.)
np.in1d(A,B)返回一个布尔数组,指示是否在B中找到A的每个值.np.where返回True值的索引。 (如果您的数组未排序,这也会有效。)
#2
4
You should start with np.intersect1d
, which finds the set intersection (common elements) between arrays.
您应该从np.intersect1d开始,它找到数组之间的集合交集(公共元素)。
In [5]: np.intersect1d(A, B)
Out[5]: array([50, 78, 85])
To get the desired output from your question, you can then use np.searchsorted
with just those items:
要从您的问题中获得所需的输出,您可以使用np.searchsorted只包含这些项:
In [7]: np.searchsorted(A, np.intersect1d(A, B))
Out[7]: array([2, 3, 4])
#1
10
You could use np.where
and np.in1d
:
你可以使用np.where和np.in1d:
>>> np.where(np.in1d(A, B))[0]
array([2, 3, 4])
np.in1d(A, B)
returns a boolean array indicating whether each value of A
is found in B
. np.where
returns the indices of the True
values. (This will also work if your arrays are not sorted.)
np.in1d(A,B)返回一个布尔数组,指示是否在B中找到A的每个值.np.where返回True值的索引。 (如果您的数组未排序,这也会有效。)
#2
4
You should start with np.intersect1d
, which finds the set intersection (common elements) between arrays.
您应该从np.intersect1d开始,它找到数组之间的集合交集(公共元素)。
In [5]: np.intersect1d(A, B)
Out[5]: array([50, 78, 85])
To get the desired output from your question, you can then use np.searchsorted
with just those items:
要从您的问题中获得所需的输出,您可以使用np.searchsorted只包含这些项:
In [7]: np.searchsorted(A, np.intersect1d(A, B))
Out[7]: array([2, 3, 4])