简体   繁体   English

Pandas无效的类型比较错误

[英]Pandas invalid type comparison error

For some reason, which I can't find in the Pandas changelog for 0.17.1, comparing a datetime series with an int value (Unix epoch) does not work anymore. 由于某些原因,我在Pandas更新日志中找不到0.17.1,将datetime系列与int值(Unix纪元)进行比较不再适用。 Could anyone please explain this or point me to the right section in the changelog? 任何人都可以解释一下,或者指向更改日志中的正确部分?

Working in 0.16.2 工作在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

Error in 0.17.1 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

You can still use an explicit conversion: 您仍然可以使用显式转换:

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

Or, if you want to rely on pandas timestamps being stored as datetime64[ns] : 或者,如果您想依赖将pandas时间戳存储为datetime64[ns]

u_time_ns = d.view('int64')

Sorry, no idea why this changed. 对不起,不知道为什么会改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM