我有一个1d数组,想找到最后一个这样的值。
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的最后一个匹配项的索引,可以使用:
现在,如果您有一个三维数组,您仍然可以使用
np.argwhere
来获取7的引用,但是每个引用都将在三维空间中。为了得到7的最后一次出现,您将再次编写它的回报完全符合你的预期。
为了得到最后一个索引,我们可以沿所有轴翻转顺序,然后对匹配项使用
np.argmax()
。翻转的思想是利用有效的np.argmax
来获得第一个匹配索引。因此,实施将是-
运行时测试-
如果你想得到一个轴上的最后一个索引,比如说
axis=0
,然后沿着两个轴迭代,比如说最后两个轴,我们可以采用相同的方法-样本运行-
相关问题 更多 >
编程相关推荐