w3resource

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


NumPy: Universal Functions Exercise-20 with Solution


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.

Python-Numpy Code Editor: