gpt4 book ai didi

Python pandas tz_localize throws NonExistentTimeError,然后无法丢弃错误的时间

转载 作者:太空宇宙 更新时间:2023-11-04 03:39:45 25 4
gpt4 key购买 nike

在 python pandas 中,我有一个如下所示的数据集:

enter image description here

对于2007-04-26 17:00:00之前的数据,时区是美国/东部。对于之后的数据,时区是美国/芝加哥。

当我运行这个时:

data.index = data[:'2007-04-26 16:59:59'].index.tz_localize('US/Eastern', ambiguous = 'NaT').tz_convert('Europe/London')

我收到一条错误消息:

NonExistentTimeError: 2006-04-02 02:00:00

这确实是因为夏令时。我在 2007 年遇到了同样的问题。随后几年我没有遇到这个问题。理想情况下,我想要两个命令 - 一个将数据集的前半部分从东部转换为伦敦,另一个将后半部分从芝加哥转换为伦敦。

由于这不起作用,我尝试删除这些时间(我相信是一个小时),例如。 02:00:00 到 03:00:00 有夏令时。但是,当我运行

data.drop(data.ix['2005-04-03 2:00:00':'2005-04-03 3:00:00'], inplace=True)

我明白了

ValueError: labels ['open' 'high' 'low' 'close' 'volume'] not contained in axis

有谁知道我如何简单地转换这些时间?任何帮助将不胜感激。

谢谢,亚历克斯

更新以添加更多信息:

enter image description here

好的,我使用了以下代码来减少违规时间:

更新 2:

mask =  ((data.index<datetime.strptime("2006-04-02 02:00:00","%Y-%m-%d %H:%S:%M")) | (data.index>datetime.strptime("2006-04-02 03:00:00","%Y-%m-%d %H:%S:%M"))) & ((data.index<datetime.strptime("2005-04-03 02:00:00","%Y-%m-%d %H:%S:%M")) | (data.index>datetime.strptime("2005-04-03 03:00:00","%Y-%m-%d %H:%S:%M"))) & ((data.index<datetime.strptime("2005-10-30 01:00:00","%Y-%m-%d %H:%S:%M")) | (data.index>datetime.strptime("2005-10-30 02:00:00","%Y-%m-%d %H:%S:%M"))) & ((data.index<datetime.strptime("2006-10-29 01:00:00","%Y-%m-%d %H:%S:%M")) | (data.index>datetime.strptime("2006-10-29 02:00:00","%Y-%m-%d %H:%S:%M")))
data_filtered = data[mask]
data_filtered.ix = data_filtered.tz_localize('US/Eastern', infer_dst=True).tz_convert('Europe/London')

但是现在我得到这个错误:

    data_filtered.ix = data_filtered.tz_localize('US/Eastern', infer_dst=True).tz_convert('Europe/London')
Traceback (most recent call last):

File "<ipython-input-38-0fc8a9e68588>", line 1, in <module>
data_filtered.ix = data_filtered.tz_localize('US/Eastern', infer_dst=True).tz_convert('Europe/London')

File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 1955, in __setattr__
object.__setattr__(self, name, value)

AttributeError: can't set attribute

对此有什么想法吗?我做了一些谷歌搜索,但找不到任何真正相关的东西..

最佳答案

根据文档中的描述,您的 drop 命令看起来不应该起作用。为了摆脱违规时间,我会在数据框上创建一个掩码,即:

from datetime import datetime
mask = ((df.index<datetime.strptime("2006-04-02 02:00:00","%Y-%m-%d %H:%S:%M") | (df.index>datetime.strptime("2006-04-02 03:00:00","%Y-%m-%d %H:%S:%M")) # probably add some more years here as or clauses

df_filtered = df[mask]

可能也有一种方法可以让 drop 工作。检查这个相关问题: Deleting rows of daylight saving time from a time indexed pandas dataframe

关于Python pandas tz_localize throws NonExistentTimeError,然后无法丢弃错误的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27068765/

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