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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32927502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:58:30  来源:igfitidea点击:

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

pythonpython-2.7pandas

提问by Nyxynyx

I'm encountering a problem passing a datetimeinto a Pandas.Series.asof:

我在将 a 传递给datetimea 时遇到问题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)

and the following error occurs

并发生以下错误

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'

Currently the index of the pandas.Seriesis <type 'time.struct_time'>

目前的索引pandas.Series<type 'time.struct_time'>

Will the problem be solved by converting datefrom struct_timeto Timestamp? If so, how can this be done?

问题可以通过date从转换为struct_time来解决Timestamp吗?如果是这样,如何做到这一点?



I tried converting dateto a datetimeobject but still received the same error message, even though type(dt)shows that its <type 'datetime.datetime'>

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

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

回答by unutbu

Pandas time Series should alwayshave an index of type DatetimeIndex. The TypeErroryou posted, can be reproduced if the Series index is a plain Indexof dtype objectcontaining time.struct_times.

Pandas 时间序列应该总是有一个类型的索引DatetimeIndex。在TypeError您发布,可如果系列指数是一个普通的再现IndexD型细胞object含有time.struct_time秒。

For example, this reproduces the TypeError:

例如,这会重现 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)

yields

产量

Cannot compare type 'Timestamp' with type 'struct_time'

The problem can be fixed by converting ts.indexto a DatetimeIndex:

问题可以通过转换ts.index为 a 来解决DatetimeIndex

ts.index = pd.to_datetime([DT.datetime.fromtimestamp(time.mktime(item)) 
                           for item in ts.index])

Then

然后

print(ts.asof('20150101'))

prints the value of tsassociated with the date 20150101:

打印ts与日期关联的值20150101

0

Better yet, don't use timetuples. Convert the sequence of dates to a DatetimeIndex as early as possible:

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

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