使用pd.Grouper按百年间隔分组DataFrame时遇OutOfBoundsDatetime错误
解决pd.Grouper按100年分组时的OutOfBoundsDatetime错误
问题原因
pandas默认的datetime类型采用纳秒精度,时间上限为2262-04-11。当使用freq='100YS'分组时,程序会尝试生成2300-01-01这类超出纳秒datetime范围的区间标签,因此触发越界错误。
两种可行的解决方法
方法1:手动生成百年分组键(推荐)
不依赖pd.Grouper的freq参数,直接从日期中提取年份计算所属百年区间,用整数作为分组依据,彻底规避datetime范围限制:
# 提取日期中的年份 df['year'] = df['years'].dt.year # 计算百年分组(如2000-2099归为2000组,2100-2199归为2100组) df['century_group'] = (df['year'] // 100) * 100 # 分组求和 result = df.groupby('century_group')['count'].sum()
执行后得到结果:
century_group 2000 1 2100 1 Name: count, dtype: int64
若需要将分组键转回datetime(注意:2100及以后年份不超过2262才可转换,超过建议保留整数):
result.index = pd.to_datetime(result.index.astype(str) + '-01-01')
方法2:使用Period类型分组
将datetime列转为Period类型,Period的时间范围远大于纳秒datetime,可支持更远的年份:
# 转为100年起始的Period类型 df['years_period'] = df['years'].dt.to_period('100YS') # 分组求和 result = df.groupby('years_period')['count'].sum()
执行后得到结果:
years_period 2000-01-01 1 2100-01-01 1 Freq: 100YS-DEC, Name: count, dtype: int64
如需转回datetime索引,直接调用:
result.index = result.index.dt.to_timestamp()
补充说明
你使用freq='50YS'时未报错,是因为50年间隔的区间标签(如2200-01-01)仍在纳秒datetime的上限(2262年)范围内,不会触发越界问题。
内容的提问来源于stack exchange,提问作者Karen Joseph
相关产品推荐
相关产品推荐

