Home > Enterprise >  How can I print out the max nos in each column of a numpy array in an object using python?
How can I print out the max nos in each column of a numpy array in an object using python?

Time:07-02

I have the below numpy array

[[7, 0, 0, 6],

 [5, 6, 6, 1],

 [4, 1, 6, 7],

 [5, 3, 4, 7]]

I want to find the max no in each column using np.max and then print out the result in an object such that output will be as shown below

[7, 6, 6, 7]

CodePudding user response:

If arr is your array, then you just need to use the max function, indicating the chosen axis:

arr.max(axis=0)

Output:

array([7, 6, 6, 7])

If you want a list instead of a numpy array:

arr.max(axis=0).tolist()

Output:

[7, 6, 6, 7]

CodePudding user response:

You can traverse the transposed array and look for the max value with np.max():

import numpy as np

m =np.array([[7, 0, 0, 6],

 [5, 6, 6, 1],

 [4, 1, 6, 7],

 [5, 3, 4, 7]])

out = [np.max(i) for i in m.transpose()]
print(out)

Output:

[7, 6, 6, 7]

CodePudding user response:

import numpy as np

m =np.array([[7, 0, 0, 6],

 [5, 6, 6, 1],

 [4, 1, 6, 7],

 [5, 3, 4, 7]])


#list
max_numbers = [max(x) for x in m]

#array
max_num_array = np.array(max_numbers)
  • Related