问题在于:
print type(tim[i]),type(st[i])
sublist = np.logical_and(st[i]<=tim,tim<=ed[i])
打印结果为:
<type 'datetime.datetime'> <type 'datetime.datetime'>
Traceback (most recent call last):
File "C:\Users\Che\workspace\excise\CCN\2014-10\VIS-reatract.py", line 64, in <module>
sublist = np.logical_and(st[i]<=tim,tim<=ed[i])
TypeError: can't compare datetime.datetime to numpy.ndarray
那么,我做什么呢? 谢谢!
答案 0 :(得分:2)
我还没有找到它发生的原因,它必须与数组操作符的哪一侧和数据类型有关。如果您使用numpy comparison functions instead,它将起作用。
d = [datetime.datetime(n,n,n) for n in xrange(1,10)]
a = np.array(d).reshape((3,3))
c = datetime.datetime(4,4,4)
>>> a
array([[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(2, 2, 2, 0, 0),
datetime.datetime(3, 3, 3, 0, 0)],
[datetime.datetime(4, 4, 4, 0, 0), datetime.datetime(5, 5, 5, 0, 0),
datetime.datetime(6, 6, 6, 0, 0)],
[datetime.datetime(7, 7, 7, 0, 0), datetime.datetime(8, 8, 8, 0, 0),
datetime.datetime(9, 9, 9, 0, 0)]], dtype=object)
>>> c
datetime.datetime(4, 4, 4, 0, 0)
>>> a >= c
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> c <= a
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
c <= a
TypeError: can't compare datetime.datetime to numpy.ndarray
>>> np.less_equal(c, a)
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
或者,如果您可以选择使用numpy.datetime64
,则Python运算符可以正常工作。
>>> a
array([['0001-01-01', '0002-02-02', '0003-03-03'],
['0004-04-04', '0005-05-05', '0006-06-06'],
['0007-07-07', '0008-08-08', '0009-09-09']], dtype='datetime64[D]')
>>> c
numpy.datetime64('0004-04-04')
>>> a >= c
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> c <= a
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>>
答案 1 :(得分:1)
比较中混合类型的问题的根源。鉴于它们代表什么,它们应该具有可比性但不是。 datetime.datetime具有毫秒精度,pd.Timestamp具有纳秒精度。
尝试转换为常见类型,例如pd.Timestamp。
import numpy as np
import pandas as pd
import datetime
rng = pd.date_range('1/1/2011', periods=2, freq='H')
somedate = datetime.datetime(2018,1,1)
type (somedate)
>>> datetime.datetime
pddate = rng.values[0]
type (pddate)
>>> numpy.datetime64
pddate > somedate
>>> TypeError: can't compare datetime.datetime to long
pd.Timestamp(pddate), pd.Timestamp(somedate)
>>> (Timestamp('2011-01-01 00:00:00'), Timestamp('2018-01-01 00:00:00'))
pd.Timestamp(pddate) < pd.Timestamp(somedate)
>>> True
pd.Timestamp(pddate) > pd.Timestamp(somedate)
>>> False