【问题标题】:Error comparing pandas DataFrame with datetime将 pandas DataFrame 与 datetime 进行比较时出错
【发布时间】:2016-08-06 06:14:16
【问题描述】:

我正在尝试在 Pandas DataFrame 和 Datetime 对象之间进行比较。

import pandas as pd
from datetime import datetime

df = pd.DataFrame({'date': [ datetime(2000, 1, 1)]})

# Works fine
test1 = df['date'] >= datetime(2000, 1, 2)
# Returns error
test2 = datetime(2000, 1, 2) <= df['date']

导致此错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-950-a1d9be25e98f> in <module>()
      7 test1 = df['date'] >= datetime(2000, 1, 2)
      8 # Returns error
----> 9 test2 = datetime(2000, 1, 2) <= df['date']

TypeError: can't compare datetime.datetime to Series

为什么第二个比较不起作用?是有错误还是执行比较的方法不正确?


运行: python 2.7、pandas 0.18、Windows 2010 服务器、anaconda

【问题讨论】:

  • 你的 numpy 版本是什么,因为这对我有用:test2 Out[222]: 0 False Name: date, dtype: bool
  • @EdChum 我在 py27 中安装了 numpy 1.10.4 但这对我不起作用。你的 numpy 版本是什么?
  • np 是 1.10.4 pandas 是 0.18.0 但 python 3.4 64 位

标签: python python-2.7 datetime pandas


【解决方案1】:

我相当肯定这是 Python2.7 的日期时间比较的一个怪癖:

考虑以下脚本,该脚本将datetime 对象与将与任何对象进行比较的对象进行比较,该对象与任何对象相比时引发NotImplemented

from datetime import datetime

class ComparesEqualClass(object):
    def __eq__(self, other):
        return True

    def __ne__(self, other):
        return not self == other

    def __lt__(self, other):
        return False

    def __gt__(self, other):
        return False

    __req__ = __eq__
    __rne__ = __ne__
    __rlt__ = __lt__
    __rgt__ = __gt__

ComparesEqual = ComparesEqualClass()

if __name__ == "__main__":
    print(ComparesEqual < datetime(2001, 1, 1))
    print(datetime(2001, 1, 1) < ComparesEqual)

在 2.7 上运行:

$ python2.7 comp_demo.py
False
Traceback (most recent call last):
  File "comp_demo.py", line 29, in <module>
    print(datetime(2001, 1, 1) < ComparesEqual)
TypeError: can't compare datetime.datetime to ComparesEqualClass

在 3.5 上:

$ python3.5 comp_demo.py
False
False

我认为 2.7 datetime 对象在右侧比较时有点过于严格。只要确保数据框位于比较器的左侧,您应该没有问题,因为数据框的 __lt____le__ 或任何方法都会被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2016-07-13
    • 2018-09-16
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多