How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d:
import numpy as np
a = np.array(xrange(11))
b = np.array([2, 7, 10])
inter = np.intersect1d(a, b)
# inter == array([ 2, 7, 10])
But how can I get the indices into a of the values in inter?
You could use the boolean array produced by
in1dto index anarange. Reversingaso that the indices are different from the values:intersect1dstill returns the same values…But
in1dreturns a boolean array:Which can be used to index a range:
To simplify the above, though, you could use
nonzero— this is probably the most correct approach, because it returns a tuple of uniform lists ofX,Y… coordinates:Or, equivalently:
The result can be used as an index to arrays of the same shape as
awith no problems.But note that under many circumstances, it makes sense just to use the boolean array itself, rather than converting it into a set of non-boolean indices.
Finally, you can also pass the boolean array to
argwhere, which produces a slightly differently-shaped result that’s not as suitable for indexing, but might be useful for other purposes.