gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:36:52 24 4
gpt4 key购买 nike

我在传递 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_timeTimestamp ?如果可以,如何实现?


我尝试转换 datedatetime对象,但仍然收到相同的错误消息,即使 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)

关于Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32927502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com