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

如何从日期时间列提取的唯一值numpy数组中移除NaN?

移除numpy数组中的NaT值

问题场景

从DataFrame的日期时间列提取日期后,获取唯一值得到的numpy数组中包含有效日期datetime.date(2018, 6, 18)和NaT,需要仅保留有效日期。现有代码及输出如下:

# 从日期时间列提取日期
main_df['date'] = main_df.DateTime.dt.date 

# 获取date列的唯一值
agg_hos =  main_df['date'].unique()

# 当前输出
array([datetime.date(2018, 6, 18), NaT], dtype=object)

期望输出:

# 目标输出
array([datetime.date(2018, 6, 18)], dtype=object)

尝试过移除numpy数组NaN值的常规方案,但未解决问题。

解决方案

方法1:先过滤无效值再取唯一值

在提取唯一值前,先过滤掉date列中的NaT,后续得到的唯一值数组自然不会包含无效值:

# 过滤NaT后再提取唯一值
agg_hos = main_df[main_df['date'].notna()]['date'].unique()

方法2:直接处理已生成的numpy数组

如果已经得到包含NaT的数组,可利用pandas的方法筛选有效元素(NaT在object类型数组中无法被numpy的isnan识别,pandas方法适配性更强):

import pandas as pd

# 筛选数组中的非NaT元素
agg_hos = agg_hos[pd.notna(agg_hos)]

方法3:提取日期时同步清理无效值

如果原始DateTime列本身包含NaT,可以在提取日期时直接排除这些行:

# 提取日期并移除含NaT的行
main_df['date'] = main_df['DateTime'].dt.date.dropna()
agg_hos = main_df['date'].unique()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 21:25:17