Editor

Discover Seasonal Patterns

Advanced · Write the code · from Time Series: Detect Trends and Anomalies in Business Data

From the lesson: Step 4: Find Seasonality Patterns

Seasonality means repeating patterns at fixed intervals. In our data, we built in a weekend boost. But in real data, you'd need to discover these patterns. Grouping by day of week and by month reveals when sales peak and dip.

Read this part of the lesson

Analyze seasonality in the sales data:

1. Add a day_of_week column using the index's dayofweek property.

2. Add a day_name column using the index's day_name() method.

3. Calculate mean sales by day of week, sorted by the day_of_week number.

4. Find the best and worst days (by mean sales).

5. Print "=== WEEKLY PATTERN ===" then each day with its mean: "{day_name}: ${mean:.2f}".

6. Print "Best day: {name} (${mean:.2f})" and "Worst day: {name} (${mean:.2f})".

import pandas as pd
import numpy as np
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90, freq='D')
base = 1000 + np.arange(90) * 5
weekend_boost = np.where(dates.dayofweek >= 5, 200, 0)
noise = np.random.normal(0, 80, 90)
sales = np.maximum(base + weekend_boost + noise, 0)
df = pd.DataFrame({'sales': np.round(sales, 2)}, index=dates)
# Analyze weekly seasonality

More Time Series exercises

All Python exercises · 50 practice problems · Practical Projects quiz