Pandas中Timestamp列相减触发OverflowError的解决求助
问题:Pandas时间戳差值判断触发整数溢出错误
需要判断Pandas中两个Timestamp列的差值是否大于n秒(n取值1-60),无需关注具体差值。原本操作简单,但因时间戳差值过大触发整数溢出错误。以下是最小可复现示例(MCVE):
import pandas as pd import pandas.testing dataframe = pd.DataFrame( { "historic": [pd.Timestamp("1900-01-01T00:00:00+00:00")], "futuristic": [pd.Timestamp("2200-01-01T00:00:00+00:00")], } ) # 目标:判断futuristic与historic的差值是否大于n秒,即: # futuristic - historic > n number_of_seconds = 1 dataframe["diff_greater_n"] = ( dataframe["futuristic"] - dataframe["historic"] ) / pd.Timedelta(seconds=1) > number_of_seconds expected_dataframe = pd.DataFrame( { "historic": [pd.Timestamp("1900-01-01T00:00:00+00:00")], "futuristic": [pd.Timestamp("2200-01-01T00:00:00+00:00")], "diff_greater_n": [True], } ) pandas.testing.assert_frame_equal(dataframe, expected_dataframe)
报错信息:
OverflowError: Overflow in int64 addition
额外背景:
- 时间戳需保留秒级精度,无需关注毫秒
- 这是数据帧上多个组合检查中的一项
- 数据帧可能包含数百万行
- 终于能在Stack Overflow上提问关于Overflow错误的问题
解决方案
方法1:直接比较偏移后的时间戳(最优)
核心思路是把futuristic - historic > n秒等价转换为futuristic > historic + n秒,完全避免计算大跨度时间差,从根源解决溢出问题:
number_of_seconds = 1 dataframe["diff_greater_n"] = dataframe["futuristic"] > dataframe["historic"] + pd.Timedelta(seconds=number_of_seconds)
这个方法是向量级运算,速度极快,完美适配百万行数据,而且不会触发任何溢出风险,完全符合需求。
方法2:转换为秒级整数后比较
如果后续需要基于秒数做其他运算,可以将Timestamp转换为秒级整数(Unix时间戳,支持1970年之前的负数时间戳),再计算差值比较:
# 转换为秒级整数(纳秒转秒,取整) historic_sec = dataframe["historic"].astype('int64') // 10**9 futuristic_sec = dataframe["futuristic"].astype('int64') // 10**9 dataframe["diff_greater_n"] = (futuristic_sec - historic_sec) > number_of_seconds
1900到2200年的秒级差值约为9.46e9,远小于int64的最大值(9e18),不会触发溢出,同时保留了秒级精度。
方法3:直接比较Timedelta对象
也可以不转换为数值,直接让时间差和目标Timedelta比较:
dataframe["diff_greater_n"] = (dataframe["futuristic"] - dataframe["historic"]) > pd.Timedelta(seconds=number_of_seconds)
这个方法也能避免溢出问题,但相比方法1,需要先计算时间差对象,效率略低一点。
内容的提问来源于stack exchange,提问作者Maurice
相关产品推荐
相关产品推荐

