Open In App

How to get index of NumPy multidimensional array in reverse order?

In this article, we will see how to get the index of the NumPy multidimensional array in reverse order.

Approach



Final Index= Total Elements In Rows – Current Index-1 

Example:



Input:

[[1,2,3,4,2],

[2,3,4,1,5],

[2,2,4,3,2],

[1,3,4,2,4]]

Output:

[4 0 4 3]

Explanation: In the above example,  we are trying to find the first occurrence indexing of ‘2’ in reverse order and we had 5 elements in each row and after backward indexing we get an array like [0, 4, 0, 1] now using our formula above.

final_list[0] => Total Elements In Rows – Current Index- 1 => 5-0-1 =>4

final_list[1] => Total Elements In Rows – Current Index- 1 => 5-4-1 =>0

final_list[2] => Total Elements In Rows – Current Index- 1 => 5-0-1 =>4

final_list[3] => Total Elements In Rows – Current Index- 1 => 5-1-1 =>3

Example 1:




#import Modules
import numpy as np
  
# initialize parameters
x = np.array([[1, 2, 3, 4, 2],
              [2, 3, 4, 1, 5],
              [2, 2, 4, 3, 2],
              [1, 3, 4, 2, 4]])  
num_cols = len(x[0])  
result = []  
  
# loop over each row
for row in x:  
    row = np.flip(row)  
    index = np.where(row == 2)  
    result.append(index[0][0])  
  
# get the final indexes
# Store the result as of the initial arrays
final_list = num_cols-np.array(result)-1
  
# print
print(final_list)  

Output:

[4 0 4 3]

Example 2:

The above method could work for string as well. In the example below we are trying to find the first occurrence indexing of ‘Sam’ in reverse order.




#import Modules
import numpy as np
  
# initialize parameters
x = np.array([["Sam", "John", "Lilly"],
              ["Sam", "Sam", "Kate"],
              ["Jack", "John", "Sam"],
              ["Sam", "Jack", "Rose"]]) 
num_cols = len(x[0]) 
result = [] 
  
# loop over each row
for row in x: 
    row = np.flip(row)  
    index = np.where(row == "Sam")  
    result.append(index[0][0]) 
  
# get the final indexes
# Store the result as of the initial arrays
final_list = num_cols-np.array(result)-1
  
# print
print(final_list)  

Output:

[0 1 2 ]

Example 3:

For Boolean data, we have the same approach, but since it has only 0 or 1 as the value we can use argmax() which 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.




# import Modules
import numpy as np
  
# initialize parameters
a = np.array([[True, False, True, True],
              [False, False, True, False],
              [False, True, True, True],
              [True, False, False, True]])
  
reversed_array = a[:, ::-1]
max_val = np.argmax(reversed_array, axis=1)
num_rows = a.shape[1]  
final_list = num_rows-1-max_val  
  
print(final_list)  

Output:

[3 2 3 3]


Article Tags :