How does the pandas series.expanding() method work?

PandasServer Side ProgrammingProgramming

The series.expanding() method is one of the window methods of pandas and it Provides expanding transformations. And it returns a window subclassed for the particular operation.

The parameters for this method are min_periods, center, axis, and method. The default value for the min_periods is 1 and it also takes an integer value. The center parameter takes a boolean value and the default one is False. In the same way, the default value for the axis parameter is 0, and for the method is ‘single’.

Example 1

In this following example, the series.expanding() method calculated the cumulative sum of the entire series object

# importing packages
import pandas as pd
import numpy as np

# create a series
s = pd.Series([1, 2, 3, 4, 5])
print(s)

# apply expanding method
result = s.expanding().sum()
print("Result:")
print(result)

Explanation

Initially, we have created a series object using a list of integers.

Output

The output is as follows −

0    1
1    2
2    3
3    4
4    5
dtype: int64

Result:
0     1.0
1     3.0
2     6.0
3    10.0
4    15.0
dtype: float64

The series.expanding() method successfully calculated the cumulative sum of series elements using the sum() function.

Example 2

Here we will calculate the cumulative mean of entire series elements using series.expanding() method and mean function.

# importing packages
import pandas as pd
import numpy as np

# create a series
s = pd.Series([1,3, 5, np.nan, 7, 9])
print(s)

# apply expanding method
result = s.expanding().mean()
print("Result:")
print(result)

Output

The output is given below −

0    1.0
1    3.0
2    5.0
3    NaN
4    7.0
5    9.0
dtype: float64

Result:
0    1.0
1    2.0
2    3.0
3    3.0
4    4.0
5    5.0
dtype: float64

The series.expanding() method calculates the cumulative average of entire series elements and the missing values are replaced by the previous value.

raja
Updated on 07-Mar-2022 07:43:15

Advertisements