How does the series.cumsum() method work in Pandas?


The pandas Series.cumsum() method is used to find the cumulative sum of the elements in a series object.

The Series.cumsum() method returns a cumulative sum with the same length as the original series object. The first element of the cumulative sum is the same as the input object.

This method has three parameters which are “axis”, “skipna” and “args” keywords. The important parameter is “skipna” which is used to exclude Nan/null values by default, if we include the missing values then we need to set it to “False”.

Example 1

# importing required packages
import pandas as pd
import numpy as np

# create a pandas Series object
series = pd.Series([9,3,8,np.nan,4])
print(series)

print("Cumulative sum: ",series.cumsum())

Explanation

In this example, we are finding the cumulative sum of the series object “series”, which is having some integer values and Nan. Here, we have applied the cumsum() method without changing the default parameter values.

Output

0 9.0
1 3.0
2 8.0
3 NaN
4 4.0
dtype: float64

Cumulative sum:
0  9.0
1 12.0
2 20.0
3  NaN
4 24.0
dtype: float64

The first element of the cumulative sum has the same element as the original series object. The cumsam() method skips the Nan values by default so that the Nan value at index position 3 is ignored.

Example 2

# importing required packages
import pandas as pd
import numpy as np

# create a pandas Series object
series = pd.Series([7,-3,18,np.nan,4,1])
print(series)

print("Cumulative sum including NA: ",series.cumsum(skipna=False))

Explanation

Same as the previous example, here also we calculated the cumulative sum, But the skipna parameter is changed to False from default True. Hence NULL values won’t be ignored.

Output

0  7.0
1 -3.0
2 18.0
3  NaN
4  4.0
5  1.0
dtype: float64

Cumulative sum including NA:
0  7.0
1  4.0
2 22.0
3 NaN
4 NaN
5 NaN
dtype: float64

Up to the Nan value, we got the cumulative sum elements. After that we got only Nan value, this is because the cumulative sum of NaN with anything that will be NaN only.

Updated on: 09-Mar-2022

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements