Python pandas.setindex()到datetime的问题

Python pandas.setindex()到datetime的问题,python,pandas,datetime,datetimeindex,Python,Pandas,Datetime,Datetimeindex,我有一个有股票市场数据的熊猫数据框。有一个日期列(“日期”) 尝试使用字符串访问日期时,我收到: KeyError: 'the label [1981-02-17 00:00:00] is not in the [index]' 我通过调用 self.data['date'] = pandas.to_datetime(self.data['date'], format="%Y-%m-%d") self.data.set_index(pandas.DatetimeIndex(self.data[

我有一个有股票市场数据的熊猫数据框。有一个日期列(“日期”)

尝试使用字符串访问日期时,我收到:

KeyError: 'the label [1981-02-17 00:00:00] is not in the [index]'
我通过调用

self.data['date'] = pandas.to_datetime(self.data['date'], format="%Y-%m-%d")
self.data.set_index(pandas.DatetimeIndex(self.data['date'], inplace=True))
这是我的班级:

class ohlcData:
    def __init__(self, ticker=None, csv=None, intrinio=False):
        if ticker is not None:
            self.ticker = ticker.upper()
        else:
            self.ticker = None

        if csv is not None:
            name_len = csv.find(".csv")
            if name_len is -1:
                raise ValueError("CSV file should be named ticker.csv where ticker is the stock ticker.")
            else:
                self.ticker = csv[0:name_len].upper()
                self.data = pandas.read_csv(csv)

                self.data['date'] = pandas.to_datetime(self.data['date'], format="%Y-%m-%d")
                self.data.set_index(self.data['date'], inplace=True)

        if not intrinio:
            self.data = pandas.DataFrame()
        else:
            self.read_from_intrinio()
主要报告的相关摘录:

aapl = ohlcData(csv="aapl.csv")
print(aapl.data.loc[datetime.date(1981, 2,17)])
导致:

KeyError: 'the label [1981-02-17] is not in the [index]'

我做错了什么?

对于初学者来说,
self.data.set\u index('date')
应该足够了。另外,您实际上是如何尝试访问它的?最后的时间可能会有所不同,这取决于您的数据df['1981-02-17']如果
df.set_index(“date”).loc[datetime.date(1981,2,17)]
,会发生什么?因为您的第二行似乎有一个打字错误
inplace=True
应该在
set\u index
内,而不是
DateTimeIndex()
。因此,如果上述方法有效,那么这就是原因。。i、 e.
self.data.set_index(pandas.DatetimeIndex(self.data['date']),inplace=True)
在尝试
df.set_index(“date”).loc[datetime.date(1981,2,17)]
i get
keyrerror:[1981-02-17]标签不在[index]中。