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

Python中如何检查DataFrame中的日期空值?

问题描述

我有一个包含日期数据的DataFrame:

date1               date2               date3
--------------------------------------------------------
16/07/2021 13:32    16/07/2021 14:25    26/07/2021 16:49
null                15/07/2021 15:14    null
31/10/2021 07:02    31/10/2021 07:11    12/11/2021 14:57
09/11/2021 16:35    10/11/2021 09:02    10/12/2021 18:45

我想要检查日期值是否为null,但尝试了以下方法均未成功:

>>> print(df['date1'][0])
16/07/2021 13:32

>>> print(df['date1'][1])
nan

>>> print(df['date1'][1] == 'null')
False

>>> print(df['date1'][1] == 'nan')
False

>>> print(df['date1'][1] == 'Nan')
False

>>> print(df['date1'][1] is None)
False

请问有解决该问题的方法吗?

解决方法

Pandas中的NaN是特殊的浮点类型空值,不能用普通的等于判断或is None识别,必须用专门的工具方法:

  • 方法1:用Pandas内置的isna()/isnull()
    这两个方法完全等价,可直接对单个元素或整列进行空值判断:

    # 检查单个元素
    print(pd.isna(df['date1'][1]))  # 输出 True
    print(pd.isnull(df['date1'][1]))  # 输出 True
    
    # 检查整列所有空值
    print(df['date1'].isna())
    # 输出结果:
    # 0    False
    # 1     True
    # 2    False
    # 3    False
    # Name: date1, dtype: bool
    
  • 方法2:用NumPy的isnan()
    针对单个元素的空值判断,也可以用NumPy的函数:

    import numpy as np
    print(np.isnan(df['date1'][1]))  # 输出 True
    
  • 额外优化:统一日期格式与空值
    如果你的日期列是字符串类型(包括原始的null字符串),建议先转换为datetime类型,自动将无效值转为时间类型空值NaT,后续判断更统一:

    df['date1'] = pd.to_datetime(df['date1'], errors='coerce')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:12:40