Python Pandas.Series.asof:无法将类型'Timestamp'与'struct_time'类型进行比较

时间:2015-10-03 21:06:39

标签: python python-2.7 pandas

我遇到了将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'>

datestruct_time转换为Timestamp可以解决问题吗?如果是这样,怎么办呢?

我尝试将date转换为datetime对象但仍收到相同的错误消息,即使type(dt)显示其<type 'datetime.datetime'>

dt = datetime.fromtimestamp(mktime(date))
return self.__series.index.asof(dt)

1 个答案:

答案 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)