Pandas中的”<="运算符对日期时间的行为出乎意料。

huangapple go评论54阅读模式
英文:

Pandas "<=" operator unexpected behaviour for datetime

问题

我有一个包含event_datetime列的分析事件表。

我想要筛选出只包括2天的pandas表,例如,2月1日和2月2日:

event_data.loc[(event_data['event_datetime'] >= '2023-02-01') & (event_data['event_datetime'] <= '2023-02-02')]

但是这段代码只返回了2023-02-01的事件,尽管我写的是小于或等于'2023-02-02'。

在SQL中,这个操作正常工作。我是不是漏掉了什么?在pandas文档中没有找到相关信息...

英文:

I do have an analytics event table with column event_datetime

I want to filter out pandas table for only 2 days, for example, Feb 1st and 2nd:

event_data.loc[(event_data[&#39;event_datetime&#39;] &gt;= &#39;2023-02-01&#39;) &amp;(event_data[&#39;event_datetime&#39;] &lt;= &#39;2023-02-02&#39;)]

But this code does return events for 2023-02-01 only, although I wrote less of equal '2023-02-02'.

In sql it works fine. Do I miss something? Did not find anything about it in pandas docs...

答案1

得分: 0

感谢@Galo do Leste和@Nick ODell的提示,问题出在列的日期时间格式上,它没有正确转换为字符串格式。

因此,如果列的类型是日期时间 - 运算符<= 不会按预期工作。在正确将列转换为字符串格式之后

event_data['event_datetime'] = event_data['event_datetime'].dt.strftime('%Y-%m-%d')

  • 它可以正常工作。
英文:

Thanks to @Galo do Leste and @Nick ODell hint, the problem was with datetime format of the column - it was not properly converted into str format.

So if column has datetime type - operator &lt;= doesnt work as it expected.
After proper column casting to string format

event_data[&#39;event_datetime&#39;] = event_data[&#39;event_datetime&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)
  • it works fine.

huangapple
  • 本文由 发表于 2023年2月6日 07:04:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定