Calculate the n-th discrete difference along the given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` 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)
| 1148 | |
| 1149 | @array_function_dispatch(_diff_dispatcher) |
| 1150 | def diff(a, n=1, axis=-1, prepend=np._NoValue, append=np._NoValue): |
| 1151 | """ |
| 1152 | Calculate the n-th discrete difference along the given axis. |
| 1153 | |
| 1154 | The first difference is given by ``out[n] = a[n+1] - a[n]`` along |
| 1155 | the given axis, higher differences are calculated by using `diff` |
| 1156 | recursively. |
| 1157 | |
| 1158 | Parameters |
| 1159 | ---------- |
| 1160 | a : array_like |
| 1161 | Input array |
| 1162 | n : int, optional |
| 1163 | The number of times values are differenced. If zero, the input |
| 1164 | is returned as-is. |
| 1165 | axis : int, optional |
| 1166 | The axis along which the difference is taken, default is the |
| 1167 | last axis. |
| 1168 | prepend, append : array_like, optional |
| 1169 | Values to prepend or append to "a" along axis prior to |
| 1170 | performing the difference. Scalar values are expanded to |
| 1171 | arrays with length 1 in the direction of axis and the shape |
| 1172 | of the input array in along all other axes. Otherwise the |
| 1173 | dimension and shape must match "a" except along axis. |
| 1174 | |
| 1175 | Returns |
| 1176 | ------- |
| 1177 | diff : ndarray |
| 1178 | The n-th differences. The shape of the output is the same as `a` |
| 1179 | except along `axis` where the dimension is smaller by `n`. The |
| 1180 | type of the output is the same as the type of the difference |
| 1181 | between any two elements of `a`. This is the same as the type of |
| 1182 | `a` in most cases. A notable exception is `datetime64`, which |
| 1183 | results in a `timedelta64` output array. |
| 1184 | |
| 1185 | See Also |
| 1186 | -------- |
| 1187 | gradient, ediff1d, cumsum |
| 1188 | |
| 1189 | Notes |
| 1190 | ----- |
| 1191 | Type is preserved for boolean arrays, so the result will contain |
| 1192 | `False` when consecutive elements are the same and `True` when they |
| 1193 | differ. |
| 1194 | |
| 1195 | For unsigned integer arrays, the results will also be unsigned. This |
| 1196 | should not be surprising, as the result is consistent with |
| 1197 | calculating the difference directly: |
| 1198 | |
| 1199 | >>> u8_arr = np.array([1, 0], dtype=np.uint8) |
| 1200 | >>> np.diff(u8_arr) |
| 1201 | array([255], dtype=uint8) |
| 1202 | >>> u8_arr[1,...] - u8_arr[0,...] |
| 1203 | array(255, np.uint8) |
| 1204 | |
| 1205 | If this is not desirable, then the array should be cast to a larger |
| 1206 | integer type first: |
| 1207 |
no test coverage detected