w3resource

NumPy: Calculate the difference between the maximum and the minimum values of a given array along the second axis


3. Range (Difference Between Max and Min) Along Second Axis

Write a NumPy program to calculate the difference between the maximum and the minimum values of a given array along the second axis.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a 2x6 array 'x' using arange and reshape
x = np.arange(12).reshape((2, 6))

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

# Calculating the difference between the maximum and minimum values along axis 1 using np.ptp()
r1 = np.ptp(x, 1)

# Calculating the difference between the maximum and minimum values along axis 1 using np.amax() and np.amin()
r2 = np.amax(x, 1) - np.amin(x, 1)

# Checking if the results obtained from np.ptp() and np.amax() - np.amin() are close
assert np.allclose(r1, r2)

# Displaying the difference between the maximum and minimum values along axis 1 of the array 'x'
print("\nDifference between the maximum and the minimum values of the said array:")
print(r1) 

Sample Output:

Original array:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]]

Difference between the maximum and the minimum values of the said array:
[5 5]

Explanation:

In the above code –

x = np.arange(12).reshape((2, 6)): Here we declare x as a 2D NumPy array of shape (2, 6), i.e., it has 2 rows and 6 columns.

np.ptp(x, 1): This line calculates the peak-to-peak value of each row of x along the axis 1, which corresponds to the columns.

r2 = np.amax(x, 1) - np.amin(x, 1): This line calculates the difference between the maximum and minimum values of each row, and stores the results in r2.

assert np.allclose(r1, r2) checks if r1 and r2 are equal within a certain tolerance. Since r1 and r2 contain the same values assert returns True


For more Practice: Solve these Related Problems:

  • Write a function that calculates the range (max - min) for each row in a 2D array using np.ptp.
  • Implement an algorithm that subtracts np.min from np.max along axis 1 and returns an array of differences.
  • Create a solution that computes the range for each row and also returns the indices of the corresponding min and max values.
  • Design a program that computes the average range of rows by first calculating each row’s range and then averaging them.

Python-Numpy Code Editor:

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

Previous: Write a NumPy program to get the minimum and maximum value of a given array along the second axis.
Next: Write a NumPy program to compute the 80th percentile for all elements in 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.