Skip to content

diff

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

Parameters:

Name Type Description Default
x SparseArray

Input sparse arrays.

required
n int

The number of times values are differenced. Default: 1.

1
axis int

The axis along which the difference is taken. Default: -1.

-1

Returns:

Name Type Description
out SparseArray

An array containing the n-th discrete difference along the given axis.

Source code in sparse/numba_backend/_common.py
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
def diff(x, axis=-1, n=1, prepend=None, append=None):
    """
    Calculates the n-th discrete difference along the given axis.

    Parameters
    ----------
    x : SparseArray
        Input sparse arrays.
    n : int
        The number of times values are differenced. Default: 1.
    axis : int
        The axis along which the difference is taken. Default: -1.

    Returns
    -------
    out : SparseArray
        An array containing the n-th discrete difference along the given axis.
    """
    if not isinstance(x, SparseArray):
        raise TypeError("`x` must be a SparseArray.")

    if axis < 0:
        axis = x.ndim + axis
    if prepend is not None:
        x = concatenate([prepend, x], axis=axis)
    if append is not None:
        x = concatenate([x, append], axis=axis)
    result = x
    for _ in range(n):
        result = result[(slice(None),) * axis + (slice(1, None),)] - result[(slice(None),) * axis + (slice(None, -1),)]
    return result