Python | Pandas Series.cumsum () to find the cumulative sum of the Series



Pandas Series.cumsum() is used to find the cumulative sum of a series. Cumulatively, the length of the returned series is the same as the input, and each item is the sum of all previous items.

Syntax: Series.cumsum (axis = None, skipna = True)

Parameters:
axis: 0 or `index` for row wise operation and 1 or `columns` for column wise operation
skipna: Skips NaN addition for elements after the very next one if True.

Result type: Series

Example # 1:
This example creates a series from a Python list using the Pandas .Series () method. The list also contains Null, and the skipna parameter remains the default, which is True.

# pandas module import

import pandas as pd

 
# numpy module import

import numpy as np

 
# compiling a list of values ​​

values ​​ = [ 3 , 4 , np.nan, 7 , 2 , 0 ]

 
# create a series from the list

series = pd.Series (values)

 
# calling method

cumsum = series.cumsum ()

 
# display
cumsum

Exit:

 3 7 NaN 14 16 16 dtype: float64 

explanation
Accumulated amount — it is the sum of the current and all previous values. As shown in the output above, the addition was done as follows

 3 3 + 4 = 7 7 + NaN = NaN 7 + 7 = 14 14 + 2 = 16 16 + 0 = 16 

Example # 2: skipna = False
This example creates a series in the same way as the example above. But the skipna parameter remains False. Therefore, NULL values ​​will not be ignored and will be added each time it appears.

# pandas module import

import pandas as pd

 
# numpy module import

import numpy as np

 
# compiling a list of values ​​

values ​​ = [ 1 , 20 , 13 , np.nan, 0 , 1 , 5 , 23 ]

 
# create a series from the list

series = pd.Series (values)

 
# calling method

cumsum = series.cumsum (skipna = False )

 
# display
cumsum

Exit:

 0 1.0 1 21.0 2 34.0 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN dtype: float64 

Explanation: As in As shown in the output, all values ​​after the first occurrence of NaN are also NaN, since any number + NaN is also NaN.