numpy array - choosing maximum based on multiple rows

Viewed 118

I want to write a function bestcolumn for a 2-dimensional numpy array that will do the following - choose the column with maximum value in row 0, if there are multiple values with the maximum in row 0, between them choose the column with maximum value in column 1 and then apply the same with column 2.

In the example below, 4 is the max value in row 0 but there are three columns 0,1,2 with the same value 4 so we search in row 1 cols 0,1,2. The max is 5 in col 1,2. We then search in col 2 for the tiebreaker and choose col 2

Is there a way to achieve this using numpy's vectorized operations (instead of using for loops and if/else statements)?

import numpy as np

A = np.asarray([[4,4,4,3],
                [3,5,5,7],
                [2,3,4,10]])
1 Answers

One way is to use numpy.lexsort but it sort all columns not only find the maximal one.

np.lexsort(-A.T)[0]
# 2
Related