Python datetime仍然给出“TypeError:仅对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但得到了'Index'的实例”

2024-04-26 22:31:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码已经为我工作了几个月,今天早上它抛出了一个错误: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

为什么这突然停止了工作?也许熊猫的后端代码正在改变?我想也许我可以使用以下方法将python datetime索引更改为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() 

但我也犯了同样的错误。谢谢你能提供的任何帮助


Tags: 代码importdatadatetimedateindex错误dt
1条回答
网友
1楼 · 发布于 2024-04-26 22:31:40

改变的是当地时间——从夏令时到标准时间。从this similar issue

A pandas datetime column also requires the offset to be the same. A column with different offsets, will not be converted to a datetime dtype. I suggest, do not convert the data to a datetime until it's in pandas.

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

Date[0]
Out[34]: '2020-10-25T00:50:00-0700'

Date[-1]
Out[35]: '2020-11-07T22:50:00-0800'

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

我以UTC而不是本地时间提取数据,然后按照建议,直到日期列显示为Pandas,我才转换为datetime。将转换添加到美国/太平洋时间后,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

相关问题 更多 >