I know that it is possible to take the n-th order discrete difference of a numpy array by using the numpy function numpy.diff()
, but is there a way to do the same with the n-th order discrete sum?
Let's say we have a numpy array, A = np.arange(10)
. The expected result for the 1st order discrete sum would be:
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17.])
which I can get from doing:
N = A.shape[0]
B = np.zeros(N-1)
for i in range(N-1):
B[i] = A[i+1] + A[i]
But is there a function available to avoid having to use a for loop?
diff() function calculates the difference between subsequent values in a NumPy array. For example, np. diff([1, 2, 4]) returns the difference array [1 2] .
To add the two arrays together, we will use the numpy. add(arr1,arr2) method. In order to use this method, you have to make sure that the two arrays have the same length. If the lengths of the two arrays are not the same, then broadcast the size of the shorter array by adding zero's at extra indexes.
sum() in Python. numpy. sum(arr, axis, dtype, out) : This function returns the sum of array elements over the specified axis.
Pythons sum iterates over the iterable (in this case the list or array) and adds all elements. NumPys sum method iterates over the stored C array and adds these C values and finally wraps that value in a Python type (in this case numpy. int32 (or numpy. int64 ) and returns it.
A[i+1]
for for i in range(N-1)
would be covered by A[1:]
and similarly A[i]
for the same iteration means A[:-1]
. So, basically you can sum these two versions of the input array to have a vectorized output in B
, like so -
B = A[:-1] + A[1:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With