首页 > 解决方案 > Comparison between datetime64[ns] and date

问题描述

I have DataFrame with values looks like this

    Date        Value 
1   2020-04-12  A
2   2020-05-12  B   
3   2020-07-12  C   
4   2020-10-12  D
5   2020-11-12  E

and I need to create new DataFrame only with dates from today (7.12) to future (in this example only rows 3, 4 and 5).

I use this code:

df1= df[df["Date"] >= date.today()]

but it gives me TypeError: Invalid comparison between dtype=datetime64[ns] and date

What am I doing wrong? Thank you!

标签: pythonpandasdatedatetime

解决方案


使用列.dt.date上的df['Date']。然后,您将日期与日期进行比较。所以:

df1 = df.loc[df['Date'].dt.date >= date.today()]

这会给你:

        Date Value
3 2020-12-07     C
4 2020-12-10     D
5 2020-12-11     E

还要确保您的日期格式实际上是正确的。例如通过 printdf['Date'].dt.month看到它给出了所有12的 's。如果不是,则您的日期字符串未正确转换。在这种情况下,df['Date'] = pd.to_datetime(df['Date'], format="%Y-%d-%m")请在创建 DataFrame 后将 Date 列转换为正确的日期时间格式。


推荐阅读