Movatterモバイル変換


[0]ホーム

URL:


SciPy

numpy.diff

numpy.diff(a,n=1,axis=-1)[source]

Calculate the n-th discrete difference along the given axis.

The first difference is given byout[n]=a[n+1]-a[n] alongthe given axis, higher differences are calculated by usingdiffrecursively.

Parameters:
a:array_like

Input array

n:int, optional

The number of times values are differenced. If zero, the inputis returned as-is.

axis:int, optional

The axis along which the difference is taken, default is thelast axis.

Returns:
diff:ndarray

The n-th differences. The shape of the output is the same asaexcept alongaxis where the dimension is smaller byn. Thetype of the output is the same as the type of the differencebetween any two elements ofa. This is the same as the type ofa in most cases. A notable exception isdatetime64, whichresults in atimedelta64 output array.

Notes

Type is preserved for boolean arrays, so the result will containFalse when consecutive elements are the same andTrue when theydiffer.

For unsigned integer arrays, the results will also be unsigned. Thisshould not be surprising, as the result is consistent withcalculating the difference directly:

>>>u8_arr=np.array([1,0],dtype=np.uint8)>>>np.diff(u8_arr)array([255], dtype=uint8)>>>u8_arr[1,...]-u8_arr[0,...]array(255, np.uint8)

If this is not desirable, then the array should be cast to a largerinteger type first:

>>>i16_arr=u8_arr.astype(np.int16)>>>np.diff(i16_arr)array([-1], dtype=int16)

Examples

>>>x=np.array([1,2,4,7,0])>>>np.diff(x)array([ 1,  2,  3, -7])>>>np.diff(x,n=2)array([  1,   1, -10])
>>>x=np.array([[1,3,6,10],[0,5,6,8]])>>>np.diff(x)array([[2, 3, 4],       [5, 1, 2]])>>>np.diff(x,axis=0)array([[-1,  2,  0, -2]])
>>>x=np.arange('1066-10-13','1066-10-16',dtype=np.datetime64)>>>np.diff(x)array([1, 1], dtype='timedelta64[D]')

Previous topic

numpy.nancumsum

Next topic

numpy.ediff1d

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp