我有一个一维数组,想像这样找到最后一个值。
a = np.array([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1])
# find the index that value(7) last appear.
np.argwhere(a >= 7).max()
# output 10
但是它适用于一维数组,那么三维数组呢。
b = np.tile(a.reshape(15,1,1), reps=(1,30,30))
# now b is 3d array and i want to use same way to the axis = 0 in 3d array.
np.argwhere(b >= 7)
# return a 2d array. It's not what i need.
虽然我可以使用 'for' 循环另一个轴,但我想通过 numpy 有效地解决它。
最佳答案
首先,要获取最后一次出现的 7 的索引,您可以使用:
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1])
indices = np.argwhere(a== 7)
last_index = indices[-1]
# 10
现在,如果您有一个 3 维数组,您仍然可以使用 np.argwhere
来获取 7 的出现次数,但每次出现都将出现在 3 维空间中。要获得最后一次出现的 7,您将再次编写
b = np.tile(a.reshape(17,1,1), reps=(1,30,30))
np.argwhere(b==7)[-1]
# [10 29 29]
返回的正是您所期望的。
关于python - 在 numpy 数组中查找最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944060/