2

I have for example

A = [[1 2 3 4 5]
     [2 4 5 8 7]
     [9 8 4 5 2]
     [1 2 4 7 2]
     [5 9 8 7 6]
     [1 2 5 4 3]]

So the shape of A = (5,6) What I want is now the max of each column and return the result as eg:

A = [[9 9 8 8 7]] with as shape (5,1)

And at the same time I would like to receive the index of the max value from each column.

Is this possible? I don't find immediatly the sollution within the np.array basic doc.

Ilse
  • 123
  • 5
  • 14
  • question has nothing to do with `neural-network` of `jupyter-notebook` - kindly do not spam irrelevant tags (removed)... – desertnaut Jul 05 '18 at 14:10

2 Answers2

4

You could use ndarray.max().

The axis keyword argument describes what axis you want to find the maximum along.

keepdims=True lets you keep the input's dimensions.

To get the indizes of the maxima in the columns, you can use the ndarray.argmax() function. You can also pass the axis argument ot this function, but there is no keepdims option.

In both commands axis=0 describes the columns, axis=1 describes the rows. The standard value axis=None would search the maximum in the entire flattened array.

Example:

import numpy as np

A = np.asarray(
    [[1, 2, 3, 4, 5],
     [2, 4, 5, 8, 7],
     [9, 8, 4, 5, 2],
     [1, 2, 4, 7, 2],
     [5, 9, 8, 7, 6],
     [1, 2, 5, 4, 3]])
print(A)

max = A.max(axis=0, keepdims=True)
max_index = A.argmax(axis=0)

print('Max:', max)
print('Max Index:', max_index)

This prints:

[[1 2 3 4 5]
 [2 4 5 8 7]
 [9 8 4 5 2]
 [1 2 4 7 2]
 [5 9 8 7 6]
 [1 2 5 4 3]]
Max: [[9 9 8 8 7]]
Max Index: [2 4 4 1 1]
M. Deckers
  • 1,151
  • 10
  • 16
  • "axis=0 describes the columns, axis=1 describes the rows". I disagree, and stating it this way is very confusing. axis=0 refers to rows, and 1 to columns. But when we take the Max along the axis-0/rows we get columnwise maxima, and vice versa. See this image for understanding axis: https://stackoverflow.com/a/52468964/14998920. – user115625 May 03 '23 at 23:15
1

you can use numpy as well.

Example:

import numpy as np

A = [[1, 2, 3, 4, 5],
 [2, 4, 5, 8, 7],
 [9, 8, 4, 5, 2],
 [1, 2, 4, 7, 2],
 [5, 9, 8, 7, 6],
 [1, 2, 5, 4, 3]]

print(A)

A=np.array(A)

print(A.max(axis=0))
mahesh
  • 9
  • 2
  • And is it possible to keep the original indexes of my max values. EG: as index for the first 9 I would not have index 0 but index 2 ? – Ilse Jul 05 '18 at 13:27
  • print(A.argmax(axis=0)) above line will give you max value indexes now you can combine both – mahesh Jul 05 '18 at 13:35