NumPy maximum()

The maximum() function is used to find the maximum value between the corresponding elements of two arrays.

Example

import numpy as np

array1 = np.array([1, 2, 3, 4, 5])  
array2 = np.array([2, 4, 1, 5, 3])  

# find the element-wise maximum of array1 and array2 result = np.maximum(array1, array2)
print(result) # Output: [2 4 3 5 5]

maximum() Syntax

The syntax of maximum() is:

numpy.maximum(array1, array2, out = None)

maximum() Arguments

The maximum() function takes following arguments:

  • array1 and array2 - two input arrays to be compared
  • out (optional) - the output array where the result will be stored

maximum() Return Value

The maximum() function returns an array containing element-wise maximum of two arrays.


Example 1: maximum() With 2-D Array

import numpy as np

# create two 2-D arrays
array1 = np.array([[1, 2, 3], [4, 5, 6]])  
array2 = np.array([[2, 4, 1], [5, 3, 2]])  

# find the element-wise maximum of array1 and array2 result = np.maximum(array1, array2)
print(result)

Output

[[2 4 3]
 [5 5 6]]

Here, maximum() compares the corresponding elements of array1 and array2 and returns a new array result with the maximum value at each position.


Example 2: Use of out Argument in maximum()

import numpy as np

array1 = np.array([1, 3, 5, 7, 9])
array2 = np.array([2, 4, 6, 8, 10])

# create an empty array with the same shape as array1
output = np.empty_like(array1)  

# compute the element-wise maximum and store the result in output np.maximum(array1, array2, out=output)
print(output)

Output

[ 2  4  6  8 10]

Here, after specifying out=output, the result of the element-wise maximum operation is stored in the output array.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges