4

I have a 2D array:

a = ([[False False False False False  True  True  True  True  True  True  True
   True  True  True  True  True  True  True  True  True  True  True  True
   True False False False]
 [False False False False  True  True  True  True  True  True  True  True
   True  True  True  True  True  True  True  True  True  True  True  True
  False False False False]])

I am trying to get the index of last occurrence of 'True' in every row. So resulting array should be

b = ([24, 23])

To find the occurence of first True, I know i can use the np.argmax().

b = np.argmax(a==True,axis=1)

Is there a function to find from the last? I tried reversing the values of array and then using np.argmax(), but it will give the index of the reversed array.

  • After you get the index in the reversed array, subtract it from the array length to get the index in the original array. – Barmar Feb 21 '21 at 17:36

2 Answers2

2

Process each row in the backwards direction and subtract the result from the row length - 1:

result = a.shape[1] - np.argmax(a[:, ::-1], axis=1) - 1

Even == True is not needed.

The result is:

array([24, 23], dtype=int64)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
1
import numpy as np
a = np.array([[False ,False, False, False, False  ,True , True , True , True  ,True , True , True,
   True , True , True , True,  True , True  ,True  ,True  ,True  ,True , True,  True,
   True, False ,False, False],
 [False ,False, False, False, False  ,True , True , True , True  ,True , True , True,
   True , True , True , True,  True , True  ,True  ,True  ,True  ,True , True,  True,
   False, False ,False, False]])

b = a[...,::-1]
c = [len(i) - np.argmax(i) - 1 for i in b]
print(c) 

list 'c' will have indices with last True value

Prajot Kuvalekar
  • 5,128
  • 3
  • 21
  • 32