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

Pandas fillna填充datetime64[ns]空值遇类型兼容及溢出问题

解决DataFrame日期列填充空值的类型兼容与溢出问题

遇到的问题

  1. 执行代码change_date["latest_change_at"].fillna("2001-01-01T00:00:00Z", inplace=True)时,报错:

Value '2001-01-01T00:00:00Z' has dtype incompatible with datetime64[ns], please explicitly cast to a compatible dtype first.
原因是字符串类型与datetime64[ns]列类型不兼容,pandas不允许直接用字符串填充日期类型列,必须传入同类型的日期对象。

  1. 改为change_date["latest_change_at"].fillna(np.datetime64('2001-01-01T00:00:00'), inplace=True)后,触发错误:

pandas._libs.tslibs.np_datetime.OutOfBoundsDatetime: Cannot cast 2001-01-01 00:00:00 to unit='ns' without overflow.
AssertionError: Did not expect new dtype datetime64[ns] to equal self.dtype datetime64[ns].
原因是numpy的datetime64对象与pandas的datetime64[ns]列存在细微兼容性差异,直接使用可能导致类型转换时的溢出或断言错误。

正确解决方案

使用pandas原生的pd.Timestamp创建兼容的日期对象,它完全适配pandas的datetime64[ns]类型,不会出现类型不兼容或溢出问题:

import pandas as pd

# 填充空值
change_date["latest_change_at"].fillna(pd.Timestamp('2001-01-01T00:00:00Z'), inplace=True)

如果你的日期列不带时区信息,也可以简化为:

change_date["latest_change_at"].fillna(pd.Timestamp('2001-01-01'), inplace=True)

补充说明

  • pd.Timestamp会自动处理时区字符串(如末尾的Z代表UTC时区),确保与目标列的时区设置匹配。
  • 避免混用numpy和pandas的日期对象,优先使用pandas提供的日期工具类,减少类型兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:32:10