Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[i] = a[i+1] - a[i]`` along the given axis, higher differences are calculated by using `diff` recursively. Parameters ---------- a : array_like Input array n
(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue)
| 1323 | |
| 1324 | @array_function_dispatch(_diff_dispatcher) |
| 1325 | def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): |
| 1326 | """ |
| 1327 | Calculate the n-th discrete difference along the given axis. |
| 1328 | |
| 1329 | The first difference is given by ``out[i] = a[i+1] - a[i]`` along |
| 1330 | the given axis, higher differences are calculated by using `diff` |
| 1331 | recursively. |
| 1332 | |
| 1333 | Parameters |
| 1334 | ---------- |
| 1335 | a : array_like |
| 1336 | Input array |
| 1337 | n : int, optional |
| 1338 | The number of times values are differenced. If zero, the input |
| 1339 | is returned as-is. |
| 1340 | axis : int, optional |
| 1341 | The axis along which the difference is taken, default is the |
| 1342 | last axis. |
| 1343 | prepend, append : array_like, optional |
| 1344 | Values to prepend or append to `a` along axis prior to |
| 1345 | performing the difference. Scalar values are expanded to |
| 1346 | arrays with length 1 in the direction of axis and the shape |
| 1347 | of the input array in along all other axes. Otherwise the |
| 1348 | dimension and shape must match `a` except along axis. |
| 1349 | |
| 1350 | .. versionadded:: 1.16.0 |
| 1351 | |
| 1352 | Returns |
| 1353 | ------- |
| 1354 | diff : ndarray |
| 1355 | The n-th differences. The shape of the output is the same as `a` |
| 1356 | except along `axis` where the dimension is smaller by `n`. The |
| 1357 | type of the output is the same as the type of the difference |
| 1358 | between any two elements of `a`. This is the same as the type of |
| 1359 | `a` in most cases. A notable exception is `datetime64`, which |
| 1360 | results in a `timedelta64` output array. |
| 1361 | |
| 1362 | See Also |
| 1363 | -------- |
| 1364 | gradient, ediff1d, cumsum |
| 1365 | |
| 1366 | Notes |
| 1367 | ----- |
| 1368 | Type is preserved for boolean arrays, so the result will contain |
| 1369 | `False` when consecutive elements are the same and `True` when they |
| 1370 | differ. |
| 1371 | |
| 1372 | For unsigned integer arrays, the results will also be unsigned. This |
| 1373 | should not be surprising, as the result is consistent with |
| 1374 | calculating the difference directly: |
| 1375 | |
| 1376 | >>> u8_arr = np.array([1, 0], dtype=np.uint8) |
| 1377 | >>> np.diff(u8_arr) |
| 1378 | array([255], dtype=uint8) |
| 1379 | >>> u8_arr[1,...] - u8_arr[0,...] |
| 1380 | 255 |
| 1381 | |
| 1382 | If this is not desirable, then the array should be cast to a larger |