微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

KeyError:按 Pandas 中时间戳的索引寻址

如何解决KeyError:按 Pandas 中时间戳的索引寻址

我正在使用 API 从 iexcloud 收集日内 1 分钟股票数据。我将数据加载到 Pandas 数据帧中,然后我试图获取一天中特定日期和特定分钟的特定数据行。我最初尝试输入原始 start 变量(它是一个日期时间对象),但没有奏效,所以我使用 to_datetime() 将日期转换为 Pandas 格式并尝试使用 print(df[ start_p]) 但这也会返回相同的错误。我尝试搜索较旧的问题但无济于事,因为我觉得这里的问题可能源于最后这个额外的“分钟”组件。下面是代码图片显示了有问题的数据框。如果您查看输入和相应的数据帧图片,您会发现它们是完全相同的字符,我尝试使用时间戳对象和字符串对象作为键,但都没有奏效。如何在此处输入适当的索引?

import pandas as pd
import datetime #so don't have to do datetime.date())
from iexfinance.stocks import get_historical_data,get_historical_inTraday
import matplotlib.pyplot as plt

api='xxx' #https://iexcloud.io/

start = datetime.datetime(2020,11,24)
end = datetime.datetime(2020,12,20)

df =get_historical_inTraday("MSFT",start,output_format='pandas',token=api )
base='df'

for i in range(2): 


start += datetime.timedelta(days=1,hours=9,minutes=30)
start_p=pd.to_datetime(start)
#print(start_p)
#df=get_historical_inTraday("MSFT",token=api)
att={'label':[215.23],'low':[213.92]} #for SO -- reproducing part of dataset
df=pd.DataFrame(att,index=[start_p])

print(df["2020-11-25 09:30:00"]) #KeyError: '2020-11-25 09:30:00'
print('here')
print(df[start_p]) #KeyError: Timestamp('2020-11-25 09:30:00')

Dataframe in question

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。