Skip to main content
 首页 » 编程设计

Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time'

2025年05月04日14落叶无声

我在传递 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) 

请您参考如下方法:

Pandas 时间序列应该总是有一个 DatetimeIndex 类型的索引。 您发布的 TypeError, 如果系列索引是 dtype object 的普通 Index 包含 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')) 

打印与日期 20150101 关联的 ts 的值:

0 

更好的是,不要使用时间元组。将日期序列转换为 DatetimeIndex 越早越好:

In [59]: pd.to_datetime(['20150101']) 
Out[59]: DatetimeIndex(['2015-01-01'], dtype='datetime64[ns]', freq=None, tz=None)