Why is np.where(...)[-1] not returning the last element in the array

Viewed 35
import numpy as np

my_array = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])

result = np.where(my_array==2)

print(result[-1])

Result: [1 9 12]
Expected: 12

Why is result[-1] not giving me the last element?

1 Answers

np.where is returning an ndarray in a tuple:

>>> import numpy as np 
>>> a = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2])  
>>> np.where(a == 2) 
(array([ 1,  9, 12], dtype=int64),)

What you want is to get the first element, which is the ndarray, and then return the last element of that array:

>> np.where(a==2)[0][-1] 
12
Related