w3resource

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

NumPy Statistics: Exercise-2 with Solution

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.

Python-Numpy Code Editor:

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

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.

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.