Finding the row with the highest average in a numpy array

 

Questions


Given the following array:

complete_matrix = numpy.array([
    [0, 1, 2, 4],
    [1, 0, 3, 5],
    [2, 3, 0, 6],
    [4, 5, 6, 0]])

I would like to identify the row with the highest average, excluding the diagonal zeros.
So, in this case, I would be able to identify complete_matrix[:,3] as being the row with the highest average.

 

 

————————————————-

Answer

You don’t need to worry about the 0s, they shouldn’t effect how the averages compare since there will presumably be one in each row. Hence, you can do something like this to get the index of the row with the highest average:

>>> import numpy as np 
>>> complete_matrix = np.array([
...     [0, 1, 2, 4],
...     [1, 0, 3, 5],
...     [2, 3, 0, 6],
...     [4, 5, 6, 0]])
>>> np.argmax(np.mean(complete_matrix, axis=1))
3

Reference:

arrays,numpy,python

Facebook Comments

Post a comment