Add "insert_zero" option for np.diff
See original GitHub issueI 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)
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
python, numpy; How to insert element at the start of an array
So I want to insert zero at start of the array, and shift the rest of the array one place forward. example: a...
Read more >numpy.diff — NumPy v1.24 Manual
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...
Read more >How To Add Zero In Front Of Number In Excel
Select the range of cells you want to enter leading zeros in. Go to the Home tab. In the Numbers section click on...
Read more >numpy.diff() in Python - GeeksforGeeks
numpy.diff(arr[, n[, axis]]) function is used when we calculate the n-th order discrete difference along the given axis.
Read more >np.diff() - A Simple Guide - YouTube
Full Tutorial: https://blog.finxter.com/ np - diff -a-simple-illustrated-guide/Email Academy: https://blog.finxter.com/email-academy/▻▻ Do you ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
The inverse of cumsum problem would also be solved by adding
include_identity
to cumsum (#6044), which is something I’ve felt a stronger need for.Maybe the best solution is to add the padding options of ediff1d to diff, and then kill ediff1d. The discussion here does kind of make it seem like ediff1d should go, as it’s kind of violating the “one way to do things” rule.