numpy.ma.diff#

ma.diff(a,/,n=1,axis=-1,prepend=<novalue>,append=<novalue>)[source]#

Calculate the n-th discrete difference along the given axis.The first difference is given byout[i]=a[i+1]-a[i] alongthe given axis, higher differences are calculated by usingdiffrecursively.Preserves the input mask.

Parameters:
aarray_like

Input array

nint, optional

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

axisint, optional

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

prepend, appendarray_like, optional

Values to prepend or append toa along axis prior toperforming the difference. Scalar values are expanded toarrays with length 1 in the direction of axis and the shapeof the input array in along all other axes. Otherwise thedimension and shape must matcha except along axis.

Returns:
diffMaskedArray

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.

See also

numpy.diff

Equivalent function in the top-level NumPy module.

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.ma.diff(u8_arr)masked_array(data=[255],             mask=False,       fill_value=np.uint64(999999),            dtype=uint8)>>>u8_arr[1,...]-u8_arr[0,...]np.uint8(255)

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

>>>i16_arr=u8_arr.astype(np.int16)>>>np.ma.diff(i16_arr)masked_array(data=[-1],             mask=False,       fill_value=np.int64(999999),            dtype=int16)

Examples

>>>importnumpyasnp>>>a=np.array([1,2,3,4,7,0,2,3])>>>x=np.ma.masked_where(a<2,a)>>>np.ma.diff(x)masked_array(data=[--, 1, 1, 3, --, --, 1],        mask=[ True, False, False, False,  True,  True, False],    fill_value=999999)
>>>np.ma.diff(x,n=2)masked_array(data=[--, 0, 2, --, --, --],            mask=[ True, False, False,  True,  True,  True],    fill_value=999999)
>>>a=np.array([[1,3,1,5,10],[0,1,5,6,8]])>>>x=np.ma.masked_equal(a,value=1)>>>np.ma.diff(x)masked_array(    data=[[--, --, --, 5],            [--, --, 1, 2]],    mask=[[ True,  True,  True, False],            [ True,  True, False, False]],    fill_value=1)
>>>np.ma.diff(x,axis=0)masked_array(data=[[--, --, --, 1, -2]],        mask=[[ True,  True,  True, False, False]],    fill_value=1)
On this page