0
0
Pandasdata~15 mins

Why window functions matter in Pandas - See It in Action

Choose your learning style9 modes available
Why window functions matter
📖 Scenario: Imagine you work in a sales team. You have daily sales data for a store. You want to see how sales change day by day and understand trends better.
🎯 Goal: You will create a small sales dataset, set a window size, calculate the rolling average sales using a window function, and print the result. This helps smooth out daily ups and downs to see trends.
📋 What You'll Learn
Create a pandas DataFrame with exact sales data
Create a variable for the window size
Use pandas rolling window function to calculate the rolling average
Print the resulting DataFrame with the rolling average column
💡 Why This Matters
🌍 Real World
Rolling averages are used in sales, finance, and weather data to smooth out short-term fluctuations and highlight longer-term trends.
💼 Career
Data analysts and scientists use window functions like rolling averages to prepare data for reports and decision-making.
Progress0 / 4 steps
1
Create the sales data
Create a pandas DataFrame called sales_data with two columns: 'date' and 'sales'. Use these exact values for 'date': '2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'. Use these exact values for 'sales': 100, 120, 130, 90, 110. Convert the 'date' column to datetime type.
Pandas
Need a hint?

Use pd.DataFrame to create the data and pd.to_datetime to convert the date column.

2
Set the window size
Create a variable called window_size and set it to 3. This will be the number of days to look back when calculating the rolling average.
Pandas
Need a hint?

Just create a variable named window_size and assign the number 3.

3
Calculate the rolling average sales
Create a new column in sales_data called 'rolling_avg'. Use the pandas rolling function on the 'sales' column with the window size window_size and calculate the mean for each window.
Pandas
Need a hint?

Use sales_data['sales'].rolling(window=window_size).mean() to get the rolling average.

4
Print the sales data with rolling average
Print the sales_data DataFrame to see the original sales and the new rolling average column.
Pandas
Need a hint?

Use print(sales_data) to show the DataFrame with the rolling average.