为什么np.where(..)[-1]不返回数组中的最后一个元素?


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])

结果:[1 9 12]
期望:12

为什么result[-1]不给我最后一个元素?

np.where返回元组中的ndarray:

>>> 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),)

您需要的是获取第一个元素,即ndarray,然后返回该数组的最后一个元素:

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