Is there any function to calculate the difference between the maximum and the minimum elements of a Numpy array?

+1 vote

Best answer

You can first find the maximum and minimum values and then subtract them. There is also a Numpy function **ptp()** [Peak to peak] that returns "maximum - minimum" value along a given axis.

Here are examples:

>>> import numpy as np

>>> aa

array([ 8, 11, 21, 34, 45, 25, 98, 67])>>> np.ptp(aa)

90

>>> bb

array([[11, 12, 13],

[14, 15, 16],

[17, 18, 19],

[20, 21, 22]])>>> np.ptp(bb, axis=0)

array([9, 9, 9])>>> np.ptp(bb, axis=1)

array([2, 2, 2, 2])>>> np.max(bb, axis=0) - np.min(bb, axis=0)

array([9, 9, 9])>>> np.max(bb, axis=1) - np.min(bb, axis=1)

array([2, 2, 2, 2])

>>>