w3resource

Use np.maximum.reduce to find maximum element along an Axis in NumPy


20. Ufunc: Maximum Reduction Along Axis

Using ufuncs in Aggregations:

Write a NumPy program that uses np.maximum.reduce to find the maximum element along a specified axis of a 2D array.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Find the maximum element along the specified axis (e.g., axis=0)
max_elements_axis0 = np.maximum.reduce(array_2d, axis=0)

# Find the maximum element along the specified axis (e.g., axis=1)
max_elements_axis1 = np.maximum.reduce(array_2d, axis=1)

# Print the original 2D array and the results
print("Original 2D Array:")
print(array_2d)

print("\nMaximum elements along axis 0:")
print(max_elements_axis0)

print("\nMaximum elements along axis 1:")
print(max_elements_axis1)

Output:

Original 2D Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Maximum elements along axis 0:
[7 8 9]

Maximum elements along axis 1:
[3 6 9]

Explanation:

  • Import NumPy Library:
    • Import the NumPy library to handle array operations.
  • Create 2D Array:
    • Define a 2D NumPy array array_2d with some example data.
  • Maximum Along Axis 0:
    • Use "np.maximum.reduce()" to find the maximum elements along axis 0 (columns) of the 2D array, storing the result in max_elements_axis0.
  • Maximum Along Axis 1:
    • Use "np.maximum.reduce()" to find the maximum elements along axis 1 (rows) of the 2D array, storing the result in 'max_elements_axis1'.
  • Finally print the original 2D array and the results of the maximum element computations along the specified axes to verify the operation.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to use np.maximum.reduce to find the maximum value along each column of a 2D array.
  • Write a Numpy program to compute the maximum element along a specified axis using np.maximum.reduce and then compare it with np.max.
  • Write a Numpy program to apply np.maximum.reduce on a 2D array with mixed positive and negative values and then identify the row with the highest maximum.
  • Write a Numpy program to combine np.maximum.reduce with a custom function that returns both the maximum value and its index along an axis.

Go to:


Previous: Combine Boolean arrays using np.logical_and in NumPy.
Next: NumPy Masked Arrays Exercises Home.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.