NumPy max()

The max() method returns the largest element of an array along an axis.


max() Syntax

The syntax of max() is:

numpy.max(array, axis = None, out = None, keepdims = <no value>, initial=<no value>, where=<no value>)

max() Arguments

The max() method takes six arguments:

  • array - input array
  • axis (optional) - axis along which maximum value is returned (int)
  • out (optional) - array to store the output
  • keepdims (optional) - whether to preserve the input array's dimension (bool)
  • initial (optional) - the minimum value of an output element (scalar)
  • where (optional) - elements to include in the maximum value calculation(array of bool)

max() Return Value

The max() method returns the largest element.

Note: If at least one element of the input array in NaN, max() will return NaN.


Example 1: max() With 2D Array

The axis argument defines how we can handle the largest element in a 2D array.

  • If axis = None, the array is flattened and the maximum of the flattened array is returned.
  • If axis = 0, the maximum of the largest element in each column is returned.
  • If axis = 1, the maximum of the largest element in each row is returned.

Output

The largest element in the flattened array:  25
The largest element in each column (axis 0):  [15 17 25]
The largest element in each row (axis 1):  [25 22]

Example 2: Use out to Store the Result in Desired Location

In our previous examples, the max() function generated a new output array.

However, we can use an existing array to store the output using the out argument.

Output

[15 19 25]

Example 3: max() With keepdims

When keepdims = True, the dimensions of the resulting array matches the dimension of an input array.

Output

Dimensions of original array:  2

 Without keepdims: 
[25 22]
Dimensions of array:  1

 With keepdims: 
 [[25]
 [22]]
Dimensions of array:  2

Without keepdims, the result is simply a one-dimensional array of indices.

With keepdims, the resulting array has the same number of dimensions as the input array.


Example 4: max() With initial

We use initial to define the minimum value max() can return. If the maximum value of the array is smaller than the initial value, initial is returned.

Output

25
26
5.0

Example 5: Use where to Find Maximum of Filtered Array

The optional argument where specifies elements to include to calculate the maximum value.

Output

Max of entire array: 50
Max of only odd elements: 47
Max of numbers less than 30: 25