Efficient way to compute intersecting values between two numpy arrays
Use numpy.in1d
:
>>> A[np.in1d(A, B)]
array([4, 6, 7, 1, 5, 4, 1, 1, 9])
You can use np.in1d
:
>>> A[np.in1d(A, B)]
array([4, 6, 7, 1, 5, 4, 1, 1, 9])
np.in1d
returns a boolean array indicating whether each value of A
also appears in B
. This array can then be used to index A
and return the common values.
It's not relevant to your example, but it's also worth mentioning that if A
and B
each contain unique values then np.in1d
can be sped up by setting assume_unique=True
:
np.in1d(A, B, assume_unique=True)
You might also be interested in np.intersect1d
which returns an array of the unique values common to both arrays (sorted by value):
>>> np.intersect1d(A, B)
array([1, 4, 5, 6, 7, 9])