2017-03-22 312 views
1

我有一個1d數組,並且想要查找像這樣的最後一個值。查找numpy數組中的最後一個值

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 

但它適合1d陣列和3D陣列。

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的有效解決。

+0

@StephenRauch對不起,應該是適用的.max() –

+0

既沒有張貼的解決方案,爲你工作? – Divakar

+0

@Divakar謝謝,它的作品。但是有一個問題,如果數組中不存在數值(例如a == 7)。它返回最大數組索引,如何解決它? –

回答

2

要獲得最後一個索引,我們可以沿着所有軸翻轉訂單,然後在比賽中使用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 

S充足的運行 -

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 
+0

它的返回1d數組有三個元素。二維數組,我想在axia = 0上應用相同的方法。像每個b [:,i,j]循環i和j。 –

+0

@LiZiming查看帖子末尾添加的修改內容。 – Divakar

1

首先,要獲得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出現,但每次出現都會在三維空間中。要獲得最後一次出現7,再次您將寫

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

它返回正是您所期望的。

+0

二維數組,我想在axia = 0上應用相同的方法。像每個b [:,i,j]循環i和j。 –

相關問題