将Pandas日时间步长转换为每年52周(最后一周8天)的时间步长
Got it, let's work through this custom weekly averaging task together. Your requirement is clear: split each year into 52 weeks starting on January 1, with the first 51 weeks being 7 days each, and the final week covering the remaining 8 days (since 51*7 + 8 = 365, matching your 365-day year scope). Here's a step-by-step implementation with Pandas:
Step 1: Verify Datetime Index
First, double-check that your DataFrame's index is properly formatted as datetime (it looks like it already is, but this is a quick sanity check):
import pandas as pd # Ensure the index is datetime type oldman.index = pd.to_datetime(oldman.index)
Step 2: Calculate Custom Week Numbers
We need to map each date to its custom week within the year. We'll do this by:
- Extracting the year for each date
- Getting the day-of-year (1 to 365)
- Assigning week numbers: days 1-357 go into weeks 1-51 (7 days each), days 358-365 go into week 52
# Add year and day-of-year columns oldman['year'] = oldman.index.year oldman['day_of_year'] = oldman.index.dayofyear # Compute custom week number oldman['custom_week'] = oldman['day_of_year'].apply( lambda x: (x - 1) // 7 + 1 if x <= 51*7 else 52 )
Let me break that lambda down:
(x-1) //7 +1converts day-of-year to a 1-based week number (e.g., days 1-7 become week 1, days 8-14 become week 2, etc.)- Any day after 357 (51*7) gets assigned to week 52, which will always have exactly 8 days for 365-day years.
Step 3: Compute Weekly Averages
Now group the data by year and custom week, then calculate the mean of the Value column:
# Group by year and custom week, calculate mean weekly_averages = oldman.groupby(['year', 'custom_week'])['Value'].mean().reset_index() # Optional: Format a readable week label (e.g., "1992-W01", "1992-W52") weekly_averages['week_id'] = weekly_averages.apply( lambda row: f"{row['year']}-W{row['custom_week']:02d}", axis=1 ) weekly_averages.set_index('week_id', inplace=True)
Quick Validation
To make sure this works, you can check the size of the 52nd week for any year:
# Check number of days in 1992's week 52 print(oldman[(oldman['year'] == 1992) & (oldman['custom_week'] == 52)].shape[0]) # Should output 8
Note on Leap Years
If your dataset includes leap years (366 days), you'll need to decide how to handle the extra day. You could either extend week 52 to 9 days, or adjust the cutoff to 356 days (so week 51 has 7 days, week 52 has 9 days). The code above assumes 365-day years as per your original description.
内容的提问来源于stack exchange,提问作者kasra545

