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.

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!

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.