w3resource

NumPy: Get the minimum and maximum value of a given array along the second axis


2. Minimum and Maximum Along Second Axis

Write a NumPy program to get the minimum and maximum value of a given array along the second axis.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a 2x2 array 'x' using arange and reshape
x = np.arange(4).reshape((2, 2))

# Displaying the original array 'x'
print("\nOriginal array:")
print(x)

# Finding and displaying the maximum value along the second axis (axis=1) using np.amax()
print("\nMaximum value along the second axis:")
print(np.amax(x, 1))

# Finding and displaying the minimum value along the second axis (axis=1) using np.amin()
print("Minimum value along the second axis:")
print(np.amin(x, 1)) 

Sample Output:

Original array:
[[0 1]
 [2 3]]

Maximum value along the second axis:
[1 3]
Minimum value along the second axis:
[0 2]

Explanation:

In the above code –

x = np.arange(4).reshape((2,2)): This line creates a 2D array of shape (2, 2) using the np.arange function and then reshape it to the desired shape using the reshape method.

np.amax(x, 1): Here np.amax(x, 1) returns the maximum value along the 1st axis (rows) of x which is a 2x2 array. This returns a 1D array with 2 elements where each element is the maximum value of its corresponding row in the original x array. np.amin(x, 1): Here

np.amin(x, 1) returns the minimum value along the 1st axis (rows) of x which is a 2x2 array. This returns a 1D array with 2 elements where each element is the minimum value of its corresponding row in the original x array.


For more Practice: Solve these Related Problems:

  • Write a function that computes the minimum and maximum for each row (axis 1) of a 2D array using np.amin and np.amax.
  • Create a program that returns the indices of the minimum and maximum elements along the second axis of a given matrix.
  • Implement a solution that computes the min and max along axis 1 and then concatenates the results into a single 2D array.
  • Develop a method that verifies the min and max along the second axis by comparing the output with a loop-based approach.

Go to:


Previous: Write a Python program to find the maximum and minimum value of a given flattened array.
Next: Write a NumPy program to calculate the difference between the maximum and the minimum values of a given array along the second axis.

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.