在numpy数组中查找最后一个值

2024-04-19 23:12:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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有效地解决它。


Tags: thetooutputindexthatvaluenp数组
2条回答

首先,要获取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

现在,如果您有一个三维数组,您仍然可以使用np.argwhere来获取7的引用,但是每个引用都将在三维空间中。为了得到7的最后一次出现,您将再次编写

b = np.tile(a.reshape(17,1,1), reps=(1,30,30))
np.argwhere(b==7)[-1]
# [10 29 29]

它的回报完全符合你的预期。

为了得到最后一个索引,我们可以沿所有轴翻转顺序,然后对匹配项使用np.argmax()。翻转的思想是利用有效的np.argmax来获得第一个匹配索引。

因此,实施将是-

def last_match_index(a, value):
    idx = np.array(np.unravel_index(((a==value)[::-1,::-1,::-1]).argmax(), a.shape))
    return a.shape - idx - 1

运行时测试-

In [180]: a = np.random.randint(0,10,(100,100,100))

In [181]: last_match_index(a,7)
Out[181]: array([99, 99, 89])

# @waterboy5281's argwhere soln
In [182]: np.argwhere(a==7)[-1]
Out[182]: array([99, 99, 89])

In [183]: %timeit np.argwhere(a==7)[-1]
100 loops, best of 3: 4.67 ms per loop

In [184]: %timeit last_match_index(a,7)
1000 loops, best of 3: 861 µs per loop

如果你想得到一个轴上的最后一个索引,比如说axis=0,然后沿着两个轴迭代,比如说最后两个轴,我们可以采用相同的方法-

a.shape[0] - (a==7)[::-1,:,:].argmax(0) - 1

样本运行-

In [158]: a = np.random.randint(4,8,(100,100,100))
     ...: m,n,r = a.shape
     ...: out = np.full((n,r),np.nan)
     ...: for i in range(n):
     ...:     for j in range(r):
     ...:         out[i,j] = np.argwhere(a[:,i,j]==7)[-1]
     ...:         

In [159]: out1 = a.shape[0] - (a==7)[::-1,:,:].argmax(0) - 1

In [160]: np.allclose(out, out1)
Out[160]: True

相关问题 更多 >