Thursday, December 26, 2024
Google search engine
HomeLanguagesCalculate the difference between the maximum and the minimum values of a...

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

Let’s see how to calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis. Here, the Second axis means row-wise.

So firstly for finding the row-wise maximum and minimum elements in a NumPy array we are using numpy.amax() and numpy.amin() functions of NumPy library respectively. then After that we simply perform subtraction on it.

numpy.amax(): This function returns maximum of an array or maximum along axis(if mentioned). 

Syntax: numpy.amax(arr, axis = None, out = None, keepdims = )

numpy.amin(): This function returns minimum of an array or minimum along axis(if mentioned). 

Syntax: numpy.amin(arr, axis = None, out = None, keepdims = )

Now, Let’s see an example:

Example 1:

Python3




# import library
import numpy as np
  
# create a numpy 2d-array
x = np.array([[100, 20, 305],
             [ 200, 40, 300]])
  
print("given array:\n", x)
  
# get maximum element row
# wise from numpy array
max1 = np.amax(x ,1)
  
# get minimum element row
# wise from numpy array
min1 = np.amin(x, 1)
  
# print the row-wise max 
# and min difference
print("difference:\n", max1 - min1)


Output:

given array:
 [[100  20 305]
 [200  40 300]]
difference:
 [285 260]

Example 2:

Python3




# import library
import numpy as np
  
# list
x = [12, 13, 14, 15, 16]
y = [17, 18, 19, 20, 21]
  
# create a numpy 2d-array
array = np.array([x, y]).reshape((2, 5))
  
print("original array:\n", array)
  
# find max and min elements
# row-wise
max1, min1 = np.amax(array, 1), np.amin(array,1)
  
# print the row-wise max 
# and min difference
print("Difference:\n", max1 - min1)


Output:

original array:
 [[12 13 14 15 16]
 [17 18 19 20 21]]
Difference:
 [4 4]

RELATED ARTICLES

Most Popular

Recent Comments