Python Pandas重采样:调整周五至周五周度数据的起止日期(月度转周度场景)
Hey there! I see you're trying to resample monthly data to a Friday-to-Friday weekly frequency, but the default resample() method is giving you a date range that doesn't match your target (1989/09/29 to 2020/12/25). Let's fix this with a more controlled approach—here's how:
The Problem with Default Resampling
When you use df.resample("W-FRI").ffill(), pandas starts generating weekly periods from the earliest date in your original dataset (1989/09/01) and ends at the last date's corresponding Friday. This doesn't respect your custom start/end dates, which is why you're getting an unexpected range.
Solution: Build a Custom Weekly Date Range
Instead of relying on resample's default behavior, we'll explicitly create the exact weekly dates you need, then map your monthly values to each week in its corresponding month. Here's the step-by-step code:
Prepare Your Monthly Data
First, make sure your date column is properly parsed as datetime, and set it as the index (converted to monthly periods for easy matching):import pandas as pd # Assuming your original data is in df_k with "Date" and your value column (e.g., "Monthly_Value") df = df_k.copy() df["Date"] = pd.to_datetime(df["Date"]) df.set_index("Date", inplace=True) # Convert index to monthly periods to simplify month-based matching df.index = df.index.to_period("M")Create Your Target Weekly Date Sequence
Usepd.date_range()to generate exactly the Fridays between your desired start and end dates:# Generate W-FRI dates from 1989/09/29 to 2020/12/25 target_weekly_dates = pd.date_range( start="1989-09-29", end="2020-12-25", freq="W-FRI" ) # Convert these dates to monthly periods to match with our monthly data index target_monthly_periods = target_weekly_dates.to_period("M")Map Monthly Values to Weekly Dates
Now we'll build the final weekly DataFrame by matching each Friday's month to the corresponding monthly value:# Initialize the weekly DataFrame with our custom dates as index weekly_df = pd.DataFrame(index=target_weekly_dates) # Pull in the monthly value for each week's month weekly_df["Weekly_Value"] = df.loc[target_monthly_periods, "Monthly_Value"].values
Alternative: Slice After Resampling
If you prefer to use your original resampling approach, you can simply slice the resulting DataFrame to your target date range—just make sure the dates exist in the resampled data:
# Your original resampling code df.set_index(pd.DatetimeIndex(df_k["Date"]), inplace=True) weekly_df = df.resample("W-FRI").ffill() # Slice to your desired date range weekly_df = weekly_df.loc["1989-09-29":"2020-12-25"]
Note: This only works if the resampled DataFrame includes both your start and end dates. If not, the explicit date range method above is more reliable.
Either way, you'll end up with a weekly dataset that strictly adheres to your desired date bounds, with each week retaining the value from its parent month.
内容的提问来源于stack exchange,提问作者Max N

