Unlock the Power of Cumulative Sums
Calculating the cumulative sum of elements in an array can be a game-changer when working with data. This is where the cumsum()
function comes in – a powerful tool that helps you achieve just that.
Understanding the Syntax
The cumsum()
function takes in several arguments, including:
- array: the input array
- axis (optional): the axis along which the cumulative sum is calculated
- dtype (optional): the data type of the returned cumulative sum
- out (optional): the output array where the result will be stored
Flexible Calculation Options
The axis
argument gives you flexibility in how you calculate the cumulative sum. For instance:
- If
axis = None
, the array is flattened and the cumulative sum of the flattened array is returned. - If
axis = 0
, the cumulative sum is calculated column-wise. - If
axis = 1
, the cumulative sum is calculated row-wise.
Real-World Examples
Let’s see the cumsum()
function in action:
Example 1: 2-D Array
In this example, we’ll calculate the cumulative sum of a 2-D array. The axis
argument defines how we calculate the sum of elements.
import numpy as np
arr = np.array([[1