Python 日期时间仍然提供"TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an



这段代码已经为我工作了几个月,今天早上它抛出了错误:TypeError:仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但得到了一个'Index'的实例

import pandas as pd
import datetime
dt=datetime.datetime.strptime
date_array=[]
for i in range(len(Date)):
date_array.append(dt(Date[i],'%Y-%m-%dT%H:%M:%S%z')) # Data downloaded with obtimezone=local
date_array=n.array(date_array)
# Wire Mountain Dataframe
W_data=pd.DataFrame(data={'Solar':WIRC1},index=date_array)
W_mask=W_data.where(W_data > 0) # Using only daytime data, when solar does not equal 0
W_mean=W_mask.resample('D').mean() #Daily mean

数据帧如下所示:

Solar
2020-10-25 00:50:00-07:00    0.0
2020-10-25 01:50:00-07:00    0.0
2020-10-25 02:50:00-07:00    0.0
2020-10-25 03:50:00-07:00    0.0
2020-10-25 04:50:00-07:00    0.0
2020-10-25 05:50:00-07:00    0.0
2020-10-25 06:50:00-07:00    0.0
2020-10-25 07:50:00-07:00    2.0
2020-10-25 08:50:00-07:00   49.0
2020-10-25 09:50:00-07:00  116.0
2020-10-25 10:50:00-07:00  155.0
2020-10-25 11:50:00-07:00  233.0
2020-10-25 12:50:00-07:00  363.0

我用作数据帧索引的数组是python datetime

type(date_array[0])
Out[24]: datetime.datetime

为什么这个突然停止工作了?也许Pandas的后端代码正在更改?我想也许我可以使用将python日期时间索引更改为Pandas

date_array=n.array(pd.to_datetime(date_array))

但是得到了:

ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

我还尝试了另一个堆栈溢出问题:

W_mean=W_mask.set_index(date_array).resample('D').mean() 

但我也犯了同样的错误。感谢您提供的任何帮助!

;某事";当地时间发生了变化,从夏令时变为标准时间。从这个类似的问题来看,

pandas日期时间列也要求偏移量相同。A.具有不同偏移量的列,将不会转换为日期时间dtype。我建议,在数据到达之前不要将其转换为日期时间熊猫。

我的数据有两个偏移量,如下所示:

Date[0]
Out[34]: '2020-10-25T00:50:00-0700'
Date[-1]
Out[35]: '2020-11-07T22:50:00-0800'

由于有两个不同的偏移量,日期没有转换为日期时间数据类型。

我用UTC而不是当地时间提取数据,然后按照建议,直到日期列在Pandas中,我才转换为日期时间。在将转换添加到美国/太平洋时间后,Pandas无缝地处理了时间变化。

import pandas as pd
Date=n.genfromtxt('WIRC1.txt',delimiter=',',skip_header=8,usecols=1,dtype=str)
W_data=pd.DataFrame(data={'Solar':WIRC1},index=pd.to_datetime(Date).tz_convert('US/Pacific'))
W_mask=W_data.where(W_data > 0) # Using only daytime data, when solar does not equal 0
W_mean=W_mask.resample('D').mean() #Daily mean

最新更新