I often find myself wanting the difference of an array along some axis, where the 0th element should just be the first entry of the array along that axis, so that the shape of the output matches that of the input. This is a pretty common requirement for people working with finite differences in any way (eg all signal processing)
Currently, I do this with the awkward use of np.insert, as demonstrated:
a = np.random.RandomState(1234).randint(12, size=(3, 4))
array([[ 3, 6, 5, 4],
[ 8, 9, 1, 7],
[ 9, 10, 11, 10]])
# Want a diff along columns of a:
np.diff(np.insert(a, 0, 0, axis=0), axis=0)
> array([[ 3, 6, 5, 4],
[ 5, 3, -4, 3],
[ 1, 1, 10, 3]])
# Which is ugly and reallocates a whole intermediate array
# It would be more convenient to go:
np.diff(a, axis=0, insert_zero=True)
This would allow us to have an easy inverse of cumsum, so that
np.all( np.cumsum(np.diff(arr, axis=1, insert_zero=True), axis=1) == arr)
I often find myself wanting the difference of an array along some axis, where the 0th element should just be the first entry of the array along that axis, so that the shape of the output matches that of the input. This is a pretty common requirement for people working with finite differences in any way (eg all signal processing)
Currently, I do this with the awkward use of
np.insert, as demonstrated:This would allow us to have an easy inverse of cumsum, so that
np.all( np.cumsum(np.diff(arr, axis=1, insert_zero=True), axis=1) == arr)