1

For example I have this np.array:

[[True, True, False, False]
[True, False, True, False]
[False, True, False, True]
[False, False, True, True]]

I want to get the the first index that is True in each row but counting from the back of the row. So expected output is a (4,) array corresponding to each row:

[1,  # First index that is True is at index 1
 2,  # First index that is True is at index 2
 3,  # First index that is True is at index 3
 3]  # First index that is True is at index 3
0

2 Answers 2

1
a = np.array(
    [[True, True, False, False],
     [True, False, True, False],
     [False, True, False, True],
     [False, False, True, True]]
)

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

np.argmax() will find the index of the highest value (for each row with axis=1). Since True is equivalent to 1 and False to 0, it'll record the index of the first True value. Simply reverse the rows so you find the "last" one and then substract this from the row length to account for the fact that you're counting backwards.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use python to reversea row and find an element: row.reverse() and row.find(True). in numpy you can use numpy.flip(row) to reverse a row and numpy.where(row == True) to find an element in a row.

import numpy as np

x = np.array([[True, True, False, False],
[True, False, True, False],
[False, True, False, True],
[False, False, True, True]])

result = []
for row in x:
    row = np.flip(row)
    index = np.where(row == True)
    result.append(index[0][0])
print(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.