我遇到了将datetime
传递到Pandas.Series.asof
的问题:
def valueAsOf(self, date):
if type(date) is str:
return time.strptime(date, '%Y%m%d')
return self.__series.index.asof(date)
发生以下错误
Traceback (most recent call last):
File "/Users/x/test.py", line 106, in <module>
print someTs.series.asof('20150101')
File "/Users/x/anaconda/envs/test/lib/python2.7/site-packages/pandas/core/series.py", line 2460, in asof
if where < start:
File "pandas/tslib.pyx", line 836, in pandas.tslib._Timestamp.__richcmp__ (pandas/tslib.c:15612)
TypeError: Cannot compare type 'Timestamp' with type 'struct_time'
目前pandas.Series
的索引为<type 'time.struct_time'>
将date
从struct_time
转换为Timestamp
可以解决问题吗?如果是这样,怎么办呢?
我尝试将date
转换为datetime
对象但仍收到相同的错误消息,即使type(dt)
显示其<type 'datetime.datetime'>
dt = datetime.fromtimestamp(mktime(date))
return self.__series.index.asof(dt)
答案 0 :(得分:6)
Pandas time Series 总是的索引类型为DatetimeIndex
。
您发布的TypeError
,
如果系列索引是包含Index
的dtype object
的普通time.struct_time
,则可以重现。
例如,这会再现TypeError:
import datetime as DT
import time
import numpy as np
import pandas as pd
x = pd.date_range('2015-1-1', '2015-1-5', freq='D')
index = [date.timetuple() for date in x.to_pydatetime()]
ts = pd.Series(np.arange(len(index)), index=index)
try:
print(ts.asof('20150101'))
except TypeError as err:
print(err)
产量
Cannot compare type 'Timestamp' with type 'struct_time'
通过将ts.index
转换为DatetimeIndex
:
ts.index = pd.to_datetime([DT.datetime.fromtimestamp(time.mktime(item))
for item in ts.index])
然后
print(ts.asof('20150101'))
打印与日期ts
关联的20150101
的值:
0
更好的是,不要使用timetuples。将日期序列转换为a DatetimeIndex尽可能早:
In [59]: pd.to_datetime(['20150101'])
Out[59]: DatetimeIndex(['2015-01-01'], dtype='datetime64[ns]', freq=None, tz=None)