The numpy.ptp() method computes the range of values (maximum - minimum) in an array along the specified axis. Here, ptp stands for peak to peak.
Example
ptp() Syntax
The syntax of the numpy.ptp() method is:
numpy.ptp(array, axis = None, out = None, keepdims = <no value>)
ptp() Arguments
The numpy.ptp() method takes the following arguments:
array- array containing numbers whose range is desired (can bearray_like)axis(optional) - axis or axes along which the range is computed (intortuple of int)out(optional) - the output array in which to place the result (ndarray)keepdims(optional) - specifies whether to preserve the dimensions of the original array (bool)
Notes: The default values of ptp() arguments have the following implications:
axis = None, i.e. the range of the entire array is taken.- By default,
keepdimswill not be passed.
ptp() Return Value
The numpy.ptp() method returns the range of values (maximum - minimum) in an array along the specified axis.
Note: If one of the elements in the given axis is NaN, numpy.ptp() also returns NaN.
Example 1: Find the Range of a ndArray
Output
Range of the entire array: 7 Range across axis 0: [[4 4] [4 4]] Range across axis 0 and 1 [6 6]
Example 2:Using Optional keepdims Argument
If keepdims is set to True, the resultant range array is of same number of dimensions as the original array.
Output
Dimensions in original array: 2 Without keepdims: [3 3 3] with dimensions 1 With keepdims: [[3 3 3]] with dimensions 2
Example 3:Using Optional out Argument
The out parameter allows us to specify an output array where the result will be stored.
Output
Range: [29. 6. 7.]
Example 4: Data Type for ptp()
The numpy.ptp() method has no parameter to specify the data type of the output array where the result will be stored. This is because it will use the same data type as the element of the original array.
Output
Range: [ 126 127 -128] Data Type of output array: int8
In this example, the given data type is np.int8 which ranges from -128 to 127.
For the third column, the peak to peak value is 127 - (-1) = 128 which goes out of range for np.int8, thus giving us -128.
Note: A negative value can be returned when the input is an array of signed integers.