python - 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!
解决方案
使用列.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 列转换为正确的日期时间格式。
推荐阅读
- r - 在ggplotly中设置滑块范围的“开始”和“结束”值
- typescript - 使用类型安全操作创建根减速器
- python - Python读取txt文件并删除包含相同部分的行
- javascript - 开玩笑:automock 模块,但仅限于 __mocks__ 中定义的模块,而不是全部
- python - “海龟”类没有“前进”属性(Python Turtle)
- botframework - 检测消息编辑的团队
- javascript - 如何在 x 轴上使用 HighChart 的列堆叠和分组图动态日期范围?
- django - 自动发布帖子
- asp.net-core-webapi - MailKit 用于在 .Net Core 中发送邮件。已建立的连接被主机中的软件中止
- python - 获取矩形遮罩的真实边界框