Kodeclik Blog
About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
Numpy is a popular Python library used for scientific computing and data analysis. It provides powerful tools for working with arrays, matrices, and vectors. One such tool is the numpy.cumsum() function, which can be used to compute the cumulative sum of elements in an array. In this blog post, we will explore how to use the numpy.cumsum() function.
Consider the following piece of code:
The output is:
This is because 1 is the cumulative sum of elements till the first element (which is just 1), 3 is the cumulative sum of elements till the second element (i.e., 1+2=3), and 6 is the cumulative sum till the third element (i.e., 1+2+3=6).
You can also use cumsum() with multidimensional arrays but you must specify the axis along which the sum needs to be computed. But first let us see what happens when we give a two-dimensional array without any additional arguments:
The output is:
In other words, what numpy.cumsum() has done is to flatten the 2D array into a 1D array and then it has computed the cumulative sum on it, yielding the array [1 3 6 10].
If we specify axis=0, like so:
we get:
Here we are performing cumulative sums along rows. Thus the first row stays the same and the second row is modified. Note that 4 = 1+3 and 6 = 2+4. If we used axis=1 we will obtain cumulative sums along the other axis. Thus:
yields:
Here note that the first column stays the same. The second column (and additional columns, if they were present) will contain the cumulative sums.
If you liked learning about numpy.cumsum(), learn about Python’s numpy.repeat() function!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.
import numpy as np
# Create a numpy array
arr = np.array([1, 2, 3])
# Compute the cumulative sum
cum_arr = np.cumsum(arr)
print(cum_arr)
[1 3 6]
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Compute the cumulative sum
cum_arr = np.cumsum(arr)
print(cum_arr)
[ 1 3 6 10]
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Compute the cumulative sum
cum_arr = np.cumsum(arr, axis=0)
print(cum_arr)
[[1 2]
[4 6]]
import numpy as np
# Create a numpy array
arr = np.array([[1, 2], [3, 4]])
# Compute the cumulative sum
cum_arr = np.cumsum(arr, axis=1)
print(cum_arr)
[[1 3]
[3 7]]