KeyError:通过索引寻址,这些索引是Pandas中的时间戳

2024-06-17 12:12:21 发布

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

我正在使用API从iexcloud收集当天1分钟的股票数据。我将数据加载到pandas数据框中,然后尝试获取一天中特定日期和分钟的特定数据行。我最初尝试输入原始的start变量(这是一个datetime对象),但不起作用,因此我使用to_datetime()将日期转换为熊猫格式,并尝试使用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",start,output_format='pandas',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


Tags: to数据对象importapipandasdfget