Cumulative sum of a NumPy array

Python Pandas Numpy: Exercise-26 with Solution

Calculate the cumulative sum of a NumPy array.

Sample Solution:

Python Code:

import numpy as np

# Create a sample NumPy array
nums = np.array([1, 2, 3, -4, 5])

# Calculate the cumulative sum
cumulative_sum = np.cumsum(nums)

# Display the cumulative sum


[1 3 6 2 7]


Here's a breakdown of the above code:

  • First we create a sample NumPy array "nums".
  • The np.cumsum(nums) function calculates the cumulative sum of the elements in the array.
  • The resulting "cumulative_sum" is a NumPy array containing the cumulative sums.
  • The result is printed, showing the cumulative sum of the array.


Flowchart: Cumulative sum of a NumPy array.

Python Code Editor:

Previous: Matrix Multiplication with NumPy.
Next: Generating and identifying unique values in a NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.