A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/numpy/numpy-cumsum-in-python/ below:

numpy.cumsum() in Python - GeeksforGeeks

numpy.cumsum() in Python

Last Updated : 04 Dec, 2024

numpy.cumsum() function is used to compute the cumulative sum of elements in an array. Cumulative sum refers to a sequence where each element is the sum of all previous elements plus itself. For example, given an array [1, 2, 3, 4, 5], the cumulative sum would be [1, 3, 6, 10, 15].

Let's implement this as well:

Python
import numpy as np

array = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(array)

print("Original array:", array)
print("Cumulative sum:", cumulative_sum)

Output:

numpy.cumsum() in Python

The numpy.cumsum() function computes the cumulative sum of array elements along a specified axis or across the entire flattened array. This function can handle both one-dimensional and multi-dimensional arrays, providing flexibility in how cumulative sums are calculated.

Syntax for numpy.cumsum() is:

numpy.cumsum(array, axis=None, dtype=None, out=None)

where,

1. Cumulative Sum of a One-Dimensional Array

To calculate the cumulative sum of a one-dimensional array:

Python
import numpy as np

array1 = np.array([1, 2, 3, 4, 5])
cumulative_sum = np.cumsum(array1)
print(cumulative_sum)  

# Output: [ 1 3 6 10 15]

This example demonstrates how each element in the resulting array represents the sum of all preceding elements including itself

2. Cumulative Sum of a Two-Dimensional Array

For two-dimensional arrays, you can specify an axis:

Python
import numpy as np

array2 = np.array([[1, 2], [3, 4]])
cumulative_sum_flattened = np.cumsum(array2)
cumulative_sum_axis0 = np.cumsum(array2, axis=0)
cumulative_sum_axis1 = np.cumsum(array2, axis=1)

print(cumulative_sum_flattened)  
print(cumulative_sum_axis0)     
print(cumulative_sum_axis1)      

Output
[ 1  3  6 10]
[[1 2]
 [4 6]]
[[1 3]
 [3 7]]
Using dtype to Specify Data Type in NumPy cumsum

The dtype parameter allows you to specify the data type of the output:

Python
import numpy as np

array3 = np.array([1, 2, 3])
cumulative_sum_float = np.cumsum(array3, dtype=float)
print(cumulative_sum_float) 

# Output: [1.0 3.0 6.0]

This ensures that the resulting cumulative sums are stored as floats.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4