2

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.

dward4
  • 1,615
  • 3
  • 15
  • 30
  • What do you mean by _"...each ith index matches between the arrays..."_? Specifically, what do you expect to be returned by such a function? – AGN Gazer Nov 02 '17 at 01:51
  • Take a look at https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.equal.html – AGN Gazer Nov 02 '17 at 01:53
  • Possible duplicate of [Comparing two numpy arrays for equality, element-wise](https://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise) – AGN Gazer Nov 02 '17 at 01:54
  • Bad phrasing, sorry. Checking for each ith element in each array if a[i] == b[i] – dward4 Nov 02 '17 at 02:16

4 Answers4

8

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)

output:

(array([3, 6]),)
dward4
  • 1,615
  • 3
  • 15
  • 30
James
  • 32,991
  • 4
  • 47
  • 70
6

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)

output:

(array([3, 6]),)
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • Thanks, I was trying to figure out np.where but was not exactly correct. Was computing a[np.where(a==b)] and other incorrect answers. – dward4 Nov 02 '17 at 02:12
3

Another variation to other answers:

np.flatnonzero(a == b)
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
0

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]),)
Sunil
  • 171
  • 2
  • 4