mwchase

numpy.diff

Aug 12th, 2011
1,088
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. def diff(a, n=1, axis=-1):
  2.     """
  3.    Calculate the n-th order discrete difference along given axis.
  4.  
  5.    The first order difference is given by ``out[n] = a[n+1] - a[n]`` along
  6.    the given axis, higher order differences are calculated by using `diff`
  7.    recursively.
  8.  
  9.    Parameters
  10.    ----------
  11.    a : array_like
  12.        Input array
  13.    n : int, optional
  14.        The number of times values are differenced.
  15.    axis : int, optional
  16.        The axis along which the difference is taken, default is the last axis.
  17.  
  18.    Returns
  19.    -------
  20.    out : ndarray
  21.        The `n` order differences. The shape of the output is the same as `a`
  22.        except along `axis` where the dimension is smaller by `n`.
  23.  
  24.    See Also
  25.    --------
  26.    gradient, ediff1d
  27.  
  28.    Examples
  29.    --------
  30.    >>> x = np.array([1, 2, 4, 7, 0])
  31.    >>> np.diff(x)
  32.    array([ 1,  2,  3, -7])
  33.    >>> np.diff(x, n=2)
  34.    array([  1,   1, -10])
  35.  
  36.    >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
  37.    >>> np.diff(x)
  38.    array([[2, 3, 4],
  39.           [5, 1, 2]])
  40.    >>> np.diff(x, axis=0)
  41.    array([[-1,  2,  0, -2]])
  42.  
  43.    """
  44.     if n == 0:
  45.         return a
  46.     if n < 0:
  47.         raise ValueError(
  48.                 "order must be non-negative but got " + repr(n))
  49.     a = asanyarray(a)
  50.     nd = len(a.shape)
  51.     slice1 = [slice(None)]*nd
  52.     slice2 = [slice(None)]*nd
  53.     slice1[axis] = slice(1, None)
  54.     slice2[axis] = slice(None, -1)
  55.     slice1 = tuple(slice1)
  56.     slice2 = tuple(slice2)
  57.     if n > 1:
  58.         return diff(a[slice1]-a[slice2], n-1, axis=axis)
  59.     else:
  60.         return a[slice1]-a[slice2]
Advertisement
Add Comment
Please, Sign In to add comment