Reputation: 1942
Given two arrays, is there a numpy non-loop way to check if each ith index matches between the arrays, aka check for every i if a[i]==b[i]?
a = np.array([1,2,3,4,5,6,7,8])
b = np.array([2,3,4,5,6,7,8,9])
Output: 0 matches
I expect this has already been asked but I could not find what I was looking for, apologies if it is.
Upvotes: 2
Views: 29540
Reputation: 181
You could try something like:
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([8,2,10,2,7,4,10,4,9,8])
np.where(a == b)
(array([1, 3, 5, 7]),)
Upvotes: 0
Reputation: 36746
Try this:
np.arange(len(a))[a==b]
It creates a new array from 0 to length a
representing the indices. Then use a==b
to slice the array, returning the indices where a
and b
are the same.
Additionally from @Reblochon-Masque:
You can use numpy.where
to extract the indices where two values meet a specified condition:
import numpy
a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
(array([3, 6]),)
Upvotes: 8
Reputation: 36722
You can use numpy.where
to extract the indices where two values meet a specified condition:
import numpy
a = numpy.array([0, 1, 2, 3, 4, 5, 6])
b = numpy.array([6, 5, 4, 3, 2, 1, 6])
numpy.where(a==b)
(array([3, 6]),)
Upvotes: 7