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

Pandas日期转换与范围校验问题求助:日期转整数失败

问题解决:Pandas日期范围校验优化与类型转换修复

错误根源是你的DataFrame中日期为字符串格式,直接转整数会失败。需先将字符串转为Pandas的datetime类型,再处理NaT值,同时用矢量化操作替代低效的双重循环。

核心修正方案(推荐矢量化实现)

import pandas as pd
import numpy as np

# 1. 将索引转为datetime类型(若原索引是字符串)
intersections_df.index = pd.to_datetime(intersections_df.index)
# 2. 将DataFrame内的日期列转为datetime,自动将无效值/空值转为NaT
intersections_df_d = intersections_df.apply(pd.to_datetime, errors='coerce')

# 3. 计算每个索引日期的10天后日期
index_plus_10d = intersections_df.index + pd.Timedelta(days=10)

# 4. 矢量化校验日期范围:判断日期是否落在[索引日期, 索引日期+10天]区间
# 同时将NaT对应的结果设为False
intersections_con = (intersections_df_d > intersections_df.index) & (intersections_df_d <= index_plus_10d)
intersections_con = intersections_con.fillna(False)

print(intersections_con)

关键说明

  • pd.to_datetime(errors='coerce'):自动将无效日期字符串、空值转为NaT,避免转换报错
  • 索引转datetime后,直接用+ pd.Timedelta(days=10)计算10天后的日期,无需手动转整数
  • 矢量化比较利用Pandas广播机制自动对齐索引与列,效率比双重循环提升数十倍
  • fillna(False)将NaT对应的校验结果统一设为False,匹配你原本的逻辑

若需强制用时间戳整数处理

如果一定要转成秒级时间戳整数,可参考以下代码:

# 将日期列转成秒级时间戳,NaT替换为-1
intersections_df_ts = intersections_df_d.apply(lambda x: x.view('int64') // 10**9).fillna(-1).astype(np.int64)
# 索引转秒级时间戳
index_ts = intersections_df.index.view('int64') // 10**9
# 计算10天后的秒级时间戳
index_plus_10d_ts = index_ts + 10*24*3600

# 范围校验,将-1对应的结果设为False
intersections_con = (intersections_df_ts > index_ts) & (intersections_df_ts <= index_plus_10d_ts)
intersections_con = intersections_con.where(intersections_df_ts != -1, False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:05:20