NumPy Tutorial NumPy Statistics NumPy References

NumPy - ptp() function

The NumPy ptp() function returns range of values (maximum - minimum) of an array or range of values along the specified axis.

The name of the function comes from the acronym for peak to peak.


numpy.ptp(a, axis=None, out=None, keepdims=<no value>)


a Required. Specify the input array.
axis Optional. Specify axis or axes along which to operate. The default, axis=None, operation is performed on flattened array.
out Optional. Specify the output array in which to place the result. It must have the same shape as the expected output.
keepdims Optional. If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Return Value

Returns range of values of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Example: ptp() of flattened array

In the example below, ptp() function is used to return the range of values present in the array.

import numpy as np
Arr = np.array([[10,20],[30, 40]])

print("Array is:")

#range of values
print("\nRange of values:", np.ptp(Arr))

The output of the above code will be:

Array is:
[[10 20]
 [30 40]]

Range of values: 30

Example: ptp() with axis parameter

When axis parameter is provided, range of values is calculated over the specified axes as shown in the example below.

import numpy as np
Arr = np.array([[10,20,30],[70,80,90]])

print("Array is:")

#Range of values along axis=0
print("\nRange of values along axis=0")
print(np.ptp(Arr, axis=0))

#Range of values along axis=1
print("\nRange of values along axis=1")
print(np.ptp(Arr, axis=1))

The output of the above code will be:

Array is:
[[10 20 30]
 [70 80 90]]

Range of values along axis=0
[60 60 60]

Range of values along axis=1
[20 20]

❮ NumPy - Functions