numpy.ptp#

numpy.ptp(a,axis=None,out=None,keepdims=<novalue>)[source]#

Range of values (maximum - minimum) along an axis.

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

Warning

ptp preserves the data type of the array. This means thereturn value for an input of signed integers with n bits(e.g.numpy.int8,numpy.int16, etc) is also a signed integerwith n bits. In that case, peak-to-peak values greater than2**(n-1)-1 will be returned as negative values. An examplewith a work-around is shown below.

Parameters:
aarray_like

Input values.

axisNone or int or tuple of ints, optional

Axis along which to find the peaks. By default, flatten thearray.axis may be negative, inwhich case it counts from the last to the first axis.If this is a tuple of ints, a reduction is performed on multipleaxes, instead of a single axis or all the axes as before.

outarray_like

Alternative output array in which to place the result. It musthave the same shape and buffer length as the expected output,but the type of the output values will be cast if necessary.

keepdimsbool, optional

If this is set to True, the axes which are reduced are leftin the result as dimensions with size one. With this option,the result will broadcast correctly against the input array.

If the default value is passed, thenkeepdims will not bepassed through to theptp method of sub-classes ofndarray, however any non-default value will be. If thesub-class’ method does not implementkeepdims anyexceptions will be raised.

Returns:
ptpndarray or scalar

The range of a given array -scalar if array is one-dimensionalor a new array holding the result along the given axis

Examples

>>>importnumpyasnp>>>x=np.array([[4,9,2,10],...[6,9,7,12]])
>>>np.ptp(x,axis=1)array([8, 6])
>>>np.ptp(x,axis=0)array([2, 0, 5, 2])
>>>np.ptp(x)10

This example shows that a negative value can be returned whenthe input is an array of signed integers.

>>>y=np.array([[1,127],...[0,127],...[-1,127],...[-2,127]],dtype=np.int8)>>>np.ptp(y,axis=1)array([ 126,  127, -128, -127], dtype=int8)

A work-around is to use theview() method to view the result asunsigned integers with the same bit width:

>>>np.ptp(y,axis=1).view(np.uint8)array([126, 127, 128, 129], dtype=uint8)
On this page