To calculate the yearly average for column A grouped by "sw_id", you'll need to:
- Ensure your DataFrame has a datetime column (or extract the year from an existing date column).
- Group by both
"sw_id" and the year, then compute the mean of column A.
✅ Solution
Assuming your DataFrame has a date column (e.g., "date"), here's how to do it:
import pandas as pd
# (Assuming 'combined_df' is the DataFrame from the previous step)
# 1. Convert 'date' column to datetime (if not already)
combined_df['date'] = pd.to_datetime(combined_df['date'])
# 2. Extract the year into a new column
combined_df['year'] = combined_df['date'].dt.year
# 3. Group by 'sw_id' and 'year', then calculate the mean of 'A'
yearly_avg = combined_df.groupby(['sw_id', 'year'])['A'].mean().reset_index()
# Display the result
print(yearly_avg)
📊 Output Example
| sw_id | year | A |
|---|
| SW_01 | 2020 | 12.5 |
| SW_01 | 2021 | 15.2 |
| SW_02 | 2020 | 10.1 |
| ... | ... | ... |
🔍 If You Don't Have a Date Column
If your data doesn't have a date column but is ordered by time (e.g., rows are in chronological order), you can:
- Assign a year manually (if you know the time range).
- Use an index-based approach (if data is yearly).
# Example: Assign years based on row count (if data is yearly)
combined_df['year'] = combined_df.index // 12 + 2020 # Assuming 12 months per year
yearly_avg = combined_df.groupby(['sw_id', 'year'])['A'].mean().reset_index()
🚀 Bonus: Monthly/Quarterly Averages
If you need monthly or quarterly averages, modify the grouping:
# Monthly average
combined_df['month'] = combined_df['date'].dt.month
monthly_avg = combined_df.groupby(['sw_id', 'year', 'month'])['A'].mean().reset_index()
# Quarterly average
combined_df['quarter'] = combined_df['date'].dt.quarter
quarterly_avg = combined_df.groupby(['sw_id', 'year', 'quarter'])['A'].mean().reset_index()
Let me know if you need adjustments! 🎯