How to perform a reverse cumulative sum on a NumPy array?

Given a NumPy array, we have to perform a reverse cumulative sum on it. By Pranit Sharma Last updated : December 27, 2023

Problem statement

The cumulative sum for an array [1,2,3,4] can be defined as [1, 1+2, 1+2+3, 1+2+3+4] i.e., [1,3,6,10].

However, reverse cumulative is done in such a way that first all the elements are added in inverse order followed by the sum of all the elements in reverse except the first element followed by the sum of all the elements in reverse except 1st two elements until only the last element is left.

For example, for an array [1,2,3,4], the reverse cumulative sum would be [4+3+2+1, 4+3+2, 4+3, 4] i.e., [10,9,7,4].

NumPy Array - Performing a reverse cumulative sum

In NumPy, we can simply find the reverse cumulative sum on an array using the indexing technique in reverse order (: :- 1) and apply cumsum on this.

Let us understand with the help of an example,

Python code to perform a reverse cumulative sum on a NumPy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([0,1,2,3,4])

# Display original array
print("original array:\n",arr,"\n")

# Performing reverse cumulative sum
res = np.cumsum(arr[::-1])[::-1] 

# Display result
print("Result:\n",res)

Output

Example: How to perform a reverse cumulative sum on a NumPy array?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.