You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中两次resample处理日降雨数据时遇问题求助

日降雨数据处理问题

我有一组日降雨数据,需求如下:

  • 计算3日降雨总量
  • 基于该总量获取每个日历月的最大3日降雨量
  • 筛选出每年11月的数据

第一步通过resample函数生成3日降雨总量数据,代码正常运行:

df_rain_3d = df_rain_1d.resample(rule='3D', on='date', label='right').sum()

但第二步按月份重采样求最大值时无法正常运行,代码如下:

df_rain_3d_m = df_rain_3d.resample(rule='1M', on='date').max().to_period('m')

问题原因

第一步执行resample后,df_rain_3d的date列已经被转换为索引(使用on='date'参数时,resample默认会将采样后的日期设置为DataFrame的索引),此时再用on='date'会找不到对应列,导致报错。

解决方法

方法1:直接对索引重采样

去掉第二步的on='date'参数,直接基于索引进行月份重采样:

df_rain_3d_m = df_rain_3d.resample('1M').max().to_period('m')

方法2:保留date列后再重采样

第一步resample后重置索引,让date回到列中,再执行第二步:

# 第一步重置索引保留date列
df_rain_3d = df_rain_1d.resample(rule='3D', on='date', label='right').sum().reset_index()
# 第二步正常按date列重采样
df_rain_3d_m = df_rain_3d.resample(rule='1M', on='date').max().to_period('m')

筛选每年11月的数据

处理完成后,通过索引的月份属性筛选11月的数据:

df_november_rain = df_rain_3d_m[df_rain_3d_m.index.month == 11]

内容的提问来源于stack exchange,提问作者YI LI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:12:35