Waleed Ahmed
Waleed Ahmed

Reputation: 93

Pandas loc gives me keyerror, index is dates

I have this dataset containing EOD stock prices

                YAR.OL     NHY.OL  ...      DNB.OL     SBO.OL
date                               ...                       
1986-03-13         NaN        NaN  ...         NaN        NaN
1986-03-14         NaN        NaN  ...         NaN        NaN
1986-03-17         NaN        NaN  ...         NaN        NaN
1986-03-18         NaN        NaN  ...         NaN        NaN
1986-03-19         NaN        NaN  ...         NaN        NaN
...                ...        ...  ...         ...        ...
2020-07-24  377.799988  26.740000  ...  144.500000  51.000000
2020-07-27  381.799988  26.350000  ...  142.199997  50.599998
2020-07-28  382.399994  26.490000  ...  142.000000  50.200001
2020-07-29  377.899994  26.389999  ...  142.100006  50.799999
2020-07-30  372.000000  25.049999  ...  137.149994  49.799999

The index is the dates. However when I try to do

df.loc[['2020-07-29']]

I get an error saying: KeyError: '2010-07-29'

or when I do:

df.loc[['2010-06-29']]

I get KeyError: "None of [Index(['2010-06-29'], dtype='object', name='date')] are in the [index]"

I have checked the index when I have printed df.index, and the value do exist.

Index([1986-03-13, 1986-03-14, 1986-03-17, 1986-03-18, 1986-03-19, 1986-03-20,
       1986-03-21, 1986-03-24, 1986-03-25, 1986-03-26,
       ...
       2020-07-17, 2020-07-20, 2020-07-21, 2020-07-22, 2020-07-23, 2020-07-24,
       2020-07-27, 2020-07-28, 2020-07-29, 2020-07-30],
      dtype='object', name='date', length=8667)

Does anyone know why this is happening?

Upvotes: 2

Views: 485

Answers (2)

dima kal
dima kal

Reputation: 29

try to access like this:

   df.loc[df['date'] == '2010-06-29']

full example:

import pandas as pd

if __name__ == '__main__':
    d = {'date': ['2020-08-01', '2020-08-02'], 'test': [3, 4]}
    df = pd.DataFrame(data=d)
    test = df.loc[df['date'] == '2020-08-01']
    print (test)

result:

        date  test
     0  2020-08-01     3

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153510

Let's change the dtype of your index to datetime to create DateTimeIndex for your dataframe.

df.index = pd.to_datetime(df.index)

Now, let's use df.loc['2010-07-29'].

Upvotes: 2

Related Questions