Pandas无效的类型比较错误

时间:2016-02-08 08:48:19

标签: python datetime pandas

出于某些原因,我在Pandas更新日志中找不到0.17.1,将datetime系列与int值(Unix纪元)进行比较不再适用。任何人都可以解释一下或指出我在更改日志中的正确部分吗?

使用0.16.2

>>> import pandas as pd
>>> import datetime
>>> d = pd.Series([datetime.datetime(2016, 1, 1), datetime.datetime(2016, 1, 1)])
>>> d
0   2016-01-01
1   2016-01-01
dtype: datetime64[ns]
>>> d.dtype
dtype('<M8[ns]')
>>> d > 10
0    True
1    True
dtype: bool

0.17.1中的错误

>>> import pandas as pd
>>> import datetime
>>> d = pd.Series([datetime.datetime(2016, 1, 1), datetime.datetime(2016, 1, 1)])
>>> d > 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/sven/tmp/pandastest/pandas-0.17.1/lib/python2.7/site-packages/pandas/core/ops.py", line 726, in wrapper
    res = na_op(values, other)
  File "/Users/sven/tmp/pandastest/pandas-0.17.1/lib/python2.7/site-packages/pandas/core/ops.py", line 657, in na_op
    raise TypeError("invalid type comparison")
TypeError: invalid type comparison

1 个答案:

答案 0 :(得分:1)

您仍然可以使用显式转换:

u_time_ns = d.apply(lambda x: x.to_datetime64().view('int64'))
u_time_ns

0    1451606400000000000
1    1451606400000000000
dtype: int64

u_time_ns > 10

0    True
1    True
dtype: bool

或者,如果您想依赖将pandas时间戳存储为datetime64[ns]

u_time_ns = d.view('int64')

抱歉,不知道为什么会改变。