Home > Software design >  Max value in matrix only considering specified columns and rows in python
Max value in matrix only considering specified columns and rows in python

Time:03-04

Is there an efficient way of finding the index of the max value in a matrix in python only considering specified columns and rows. I have looked into the documentation of numpy but I can't seem to figure out a way to do it. I have the feeling there must be a function I keep overlooking.


matrix = [[5, 3, 6, 8],
         [4, 2, 8, 0],
         [2, 9, 10, 8],
         [3, 6, 9, 3]]

Considering the matrix above, and for example that I wanted the max value only considering the third row and the first and the third column, the result of the operation should be (2,2) considering 10 in the max value of the specified columns and rows.

CodePudding user response:

Numpy could do want you want

import numpy as np
    
x = np.array([ [7, 0, 2, 4],
      [4, 8, 5, 7],
      [4, 4, 64, 3],
      [1, 3, 1, 0] ])
  
print("Column:")  
print(x.max(axis=0)) 
print('Row:')
print(x.max(axis=1)) 

print("Max column 1")
print(x.max(axis=0)[1])

Using this you can compute the max for each row or column and then select the result based on the column you want.

CodePudding user response:

Check this out pal it's from numpy doc:

numpy.amax(a, axis=None, out=None, keepdims=, initial=, where=)[source] Return the maximum of an array or maximum along an axis.

numpy.amax()

CodePudding user response:

IIUC, you want to subset the array by row/column before getting the max?

You can use numpy.ix_:

np.random.seed(0)
a = np.random.randint(10, size=(5,5))
# [[5 0 3 3 7]
#  [9 3 5 2 4]
#  [7 6 8 8 1]
#  [6 7 7 8 1]
#  [5 9 8 9 4]]

# list of row/cols to keep
cols = (0,1,4)
rows = (0,2)

a[np.ix_(rows,cols)]
# [[5 0 7]
#  [7 6 1]]

a[np.ix_(rows,cols)].max()
# 7
  • Related