0

I'm trying to find the index of a numpy array by value. The value however is also an array. In other words, it's a multi dimensional array.

For example:

a = [
[[1, 0], [0, 2], [3, 3]], 
[[1, 0], [1, 3], [1, 0]], 
[[4, 0], [2, 3], [3, 0]]
]

I want to find the index of [[1, 0], [1, 3], [1, 0]], which is 1. Basically, I want to find the element in the array which matches the array pattern that I have.

How can I do this using numpy?

Carven
  • 14,988
  • 29
  • 118
  • 161
  • 1
    Possible duplicate of [Is there a Numpy function to return the first index of something in an array?](https://stackoverflow.com/questions/432112/is-there-a-numpy-function-to-return-the-first-index-of-something-in-an-array) –  Nov 23 '17 at 05:19
  • It isn't a perfect duplicate, so I'm not very inclined to close this. – cs95 Nov 23 '17 at 05:31

2 Answers2

2

Use np.flatnonzero in conjunction with broadcasted comparison:

a

array([[[1, 0],
        [0, 2],
        [3, 3]],

       [[1, 0],
        [1, 3],
        [1, 0]],

       [[4, 0],
        [2, 3],
        [3, 0]]])

np.flatnonzero((a == [[1, 0], [1, 3], [1, 0]]).all(1).all(1))
array([1])

Borrowing from the other answer, you could pass multiple axes to all:

np.flatnonzero((a == [[1, 0], [1, 3], [1, 0]]).all((1, 2)))
array([1])
cs95
  • 379,657
  • 97
  • 704
  • 746
1

You can use np.all and np.where:

 np.where(np.all(a==template, axis=(1,2)))[0][0]
 # 1
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99