如何在Pandas月度重采样时保留初始日期而非月初日期?
Great question! I’ve run into similar edge cases when working with time series resampling in Pandas. Unfortunately, there’s no built-in parameter for resample() or pd.Grouper that lets you override the index for just the first group directly. But we can get your desired output with a quick, clean post-processing step that’s easy to implement.
Let’s Start with Your Reproducible Code
First, let’s confirm the default behavior you’re seeing:
import pandas as pd from numpy.random import random # Generate test time series index = pd.date_range('20200112', '20210630') df = pd.Series(random(len(index)), index=index) # Default monthly resampling (sums values, uses month start dates) default_result = df.resample('MS').sum() print(default_result.head(2))
This outputs:
2020-01-01 8.613978 2020-02-01 14.614601 Freq: MS, dtype: float64
As you noted, the first index gets replaced with 2020-01-01 instead of keeping the original start date 2020-01-12.
Solution: Override the First Index Value
Here’s how to adjust the result to keep your original first date while leaving all other month-start dates intact:
# Perform the standard resampling first resampled_df = df.resample('MS').sum() # Grab the original first date from your raw time series original_first_date = df.index[0] # Replace the first index entry with the original date resampled_df.index = [original_first_date] + list(resampled_df.index[1:]) # Check the result print(resampled_df.head(2))
This will give you exactly what you want:
2020-01-12 8.613978 2020-02-01 14.614601 dtype: float64
Why This Works
Pandas’ resample() uses standardized frequency rules (like MS for month start) to set index values for all groups uniformly. There’s no way to make a single group exempt from this rule during the resampling process. However, modifying the index after resampling is lightweight and doesn’t affect the aggregated values at all.
If you want to keep the frequency metadata (the Freq: MS label), note that this will disappear after replacing the first index (since 2020-01-12 isn’t a month start). But if your priority is the correct date label for the first group, this tradeoff is usually acceptable.
内容的提问来源于stack exchange,提问作者gonzalo mr

