Code Explanation:
1. Importing Pandas
import pandas as pd
Loads the pandas library and assigns it the alias pd.
This lets us use pandas objects like Series and functions like rolling() and mean().
2. Creating a Series
s = pd.Series([1, 2, 3, 4, 5])
pd.Series() creates a 1D labeled array.
Here, the values are [1, 2, 3, 4, 5].
Default index is [0, 1, 2, 3, 4].
So the Series looks like:
0 1
1 2
2 3
3 4
4 5
dtype: int64
3. Rolling Window Operation
s.rolling(2)
.rolling(2) creates a rolling (or moving) window of size 2.
It means pandas will look at 2 consecutive values at a time.
For our Series [1, 2, 3, 4, 5], the rolling windows are:
Window 1: [1, 2]
Window 2: [2, 3]
Window 3: [3, 4]
Window 4: [4, 5]
Important: The very first element (1) has no previous element to pair with (since window size = 2), so its result will be NaN.
4. Taking the Mean
s.rolling(2).mean()
Calculates the mean (average) for each window:
Window Values Mean
[1] Not enough values → NaN
[1, 2] (1+2)/2 = 1.5
[2, 3] (2+3)/2 = 2.5
[3, 4] (3+4)/2 = 3.5
[4, 5] (4+5)/2 = 4.5
So the result is:
0 NaN
1 1.5
2 2.5
3 3.5
4 4.5
dtype: float64
5. Converting to List
.tolist()
Converts the pandas Series into a normal Python list.
Final list:
[nan, 1.5, 2.5, 3.5, 4.5]
Final Output:
[nan, 1.5, 2.5, 3.5, 4.5]
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment