使用pandas.Series.asof时出错:无法将datetime.datetime与str进行比较

时间:2015-10-09 00:16:09

标签: python python-2.7 pandas

如何使用Series.asof函数?我传递了一个datetime对象datetime.strptime('20150101', '%Y%m%d'),但为什么会出错

  File "/Users/x/anaconda/envs/test/lib/python2.7/site-packages/pandas/core/series.py", line 2460, in asof
    if where < start:
TypeError: can't compare datetime.datetime to str

使用的代码是:

import pandas as pd
from datetime import datetime

names = ['mary', 'john', 'tom']
dates = [datetime.strptime('20130101', '%Y%m%d'), 
         datetime.strptime('20140101', '%Y%m%d'), 
         datetime.strptime('20150101', '%Y%m%d')]
mySeries = pd.Series(dates, names)

print mySeries.asof(datetime.strptime('20140101', '%Y%m%d'))

我是如何错误地使用它的?

1 个答案:

答案 0 :(得分:1)

mySeries中的数据和索引相反。索引必须是TimeSeries。

mySeries = pd.Series(data=names, index=dates)
>>> print mySeries.asof(datetime.strptime('20140101', '%Y%m%d'))
john