【问题标题】:removing nan from the datetime np.array: array extracted from datetime column with unique values从日期时间 np.array 中删除 nan:从具有唯一值的日期时间列中提取的数组
【发布时间】:2022-11-17 17:03:20
【问题描述】:

我有以下列表有两个值,一个是datetime.datetime(2018-06-18),另一个是NaN。两者都是从日期时间列中提取的唯一值。我只想列表只包含日期。

# extracting date from datetime column
main_df['date'] = main_df.DateTime.dt.date 

# getting only unique values from date column
agg_hos =  main_df['date'].unique()

# output is
array([datetime.date(2018, 6, 18), NaT], dtype=object)

想要从列表中删除 nan 从网站尝试了不同的答案 remove nan values from np array

# desired output
array([datetime.date(2018, 6, 18)], dtype=object)

怎么做?

【问题讨论】:

  • 注意 NaT 是 pandas 类型,numpy 不知道

标签: python arrays pandas datetime


【解决方案1】:

您可以改用pd.isnull检查(从this answer借用):

import datetime
import numpy as np
import pandas as pd

# np.isfinite(pd.NaT), np.isnan(pd.NaT)
# -> TypeError !

arr = np.array([datetime.date(2018, 6, 18), pd.NaT])

arr = arr[~pd.isnull(arr)]
# array([datetime.date(2018, 6, 18)], dtype=object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2019-01-23
    • 1970-01-01
    • 2013-01-18
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多