将带有 NAT 条目的 pandas 日期时间字段转换为日期

convert pandas datetime field with NAT entries to date

我有一个 Pandas 数据框,其字段是日期时间数据类型。该字段中的大多数值都是有效的日期时间值,但有些是 NAT。

我需要删除字段中每个值的日期时间值的时间部分,将字段保持为日期数据类型(而不是 str)。我尝试了以下方法:

df['mydate'] =  df['mydate'].dt.date

如果列中没有 NAT 值,它工作正常。但是,如果有 NAT 值,则会抛出此错误

{AttributeError}Can only use .dt accessor with datetimelike values

我试过这个替代方法来跳过 NAT:

df['mydate'] = [d.date if not pd.isnull(d) else None for d in df['mydate']]

但这会将列中的值转换为:

<built-in method date of Timestamp object at 0x000002A06F6501C8>

请指教如何在转换时忽略或跳过字段中的NAT。我没有运气用谷歌搜索答案,我试图避免在整个数据帧上使用 iterrows() 循环。

首先将值转换为日期时间,然后正常工作 dt.date 函数:

df  = pd.DataFrame({'mydate':['2015-04-04','2018-09-10', np.nan]})

df['new'] =  pd.to_datetime(df['mydate'], errors='coerce').dt.date
print (df)
       mydate         new
0  2015-04-04  2015-04-04
1  2018-09-10  2018-09-10
2         NaN         NaT