0

I'm trying to locate a specific date within a column of a DataFrame using the df.loc function but I suddenly started getting a KeyError. This method has always worked for me but somehow, it throws a KeyError on this specific problem.

I have the following code:

import pandas as pd
from datetime import timedelta
import datetime
from datetime import datetime as dt


x = pd.read_csv('x_data.csv')

# x
#   type      date   color
# 0    A  10/16/18  orange
# 1    B  10/15/18     red
# 2    C  10/12/18    blue


x['date'] = x['date'].apply(lambda xl: datetime.datetime.strptime(xl, '%m/%d/%y'))
x['date'] = x['date'].apply(lambda xl: datetime.datetime.strftime(xl, '%Y-%m-%d'))
d = '2018-10-15'

# x
#   type        date   color
# 0    A  2018-10-16  orange
# 1    B  2018-10-15     red
# 2    C  2018-10-12    blue

I then try to use df.loc to locate d within the date column with the following line:

x = x.loc[x['date']] == d

Which returns error:

KeyError: 'None of [0    2018-10-16\n1    2018-10-15\n2    2018-10-12\nName: date, dtype: object] are in the [index]'

I cannot figure this problem out because I have been using this method for a while for various datasets a have never encountered a problem until now. Thank you for your help.

michael0196
  • 1,497
  • 1
  • 9
  • 21

0 Answers0