如何用Pandas将单年月度值拆分扩展至多年度日度数据?
问题:用Pandas将单一年份日度数据扩展到1980-2020年
我需要获取1980-2020年范围的日度数据,目前仅拥有单一年份的数据。但在将该年份的日度值复制到其余年份时遇到问题,请问如何用Pandas实现这一操作?
初始处理代码
ETPc.index=pd.to_datetime(ETPc.index, format="%m") ETPc=ETPc.reindex(pd.date_range(ETPc.index.min(), ETPc.index.max() + pd.offsets.MonthEnd(), name='date'),method='ffill') ETPc=ETPc.div(ETPc.index.daysinmonth, axis=0).reset_index()
问题代码
years=pd.period_range(1980,2020, freq='Y') myindex=(np.repeat(years,366).astype(str)+ETPc.index) ETPc.index=myindex for year in np.arange(1980,2020): if ~calendar.isleap(year): ETPc.drop(index=str(year)+'02-29',inplace=True) ETPc.index=pd.to_datetime(ETPc.index,format='%Y%m-%d')
解决方案
直接通过月日匹配+日期范围生成的方式实现,无需手动处理闰年问题,步骤如下:
代码示例
import pandas as pd # 确保原始数据的索引是日度日期格式(若未转换) ETPc.index = pd.to_datetime(ETPc.index) # 提取原始数据的「月-日」作为匹配键,重置索引方便后续合并 ETPc['month_day'] = ETPc.index.strftime('%m-%d') ETPc = ETPc.reset_index(drop=True) # 生成1980-2020年的完整日度日期范围 full_dates = pd.date_range(start='1980-01-01', end='2020-12-31', freq='D') full_df = pd.DataFrame({'date': full_dates}) # 为新日期提取「月-日」,与原始数据合并填充对应值 full_df['month_day'] = full_df['date'].strftime('%m-%d') # 替换成你的数据列名,比如ETPc的数值列是'ETP'就写['month_day', 'ETP'] full_df = full_df.merge(ETPc[['month_day', 'your_value_column']], on='month_day', how='left') # 整理最终结果:设置日期为索引,清理冗余列 full_df = full_df.set_index('date').drop(columns=['month_day'])
方法优势
- 自动处理闰年:
pd.date_range会自动跳过非闰年的2月29日,无需循环判断删除,避免索引拼接错误 - 逻辑简洁:通过「月-日」匹配直接映射数据,无需手动重复年份拼接索引
- 稳定性高:避免了原代码中字符串拼接索引可能出现的格式问题
内容的提问来源于stack exchange,提问作者faquimbayal
相关产品推荐
相关产品推荐

