Cannot find index of corresponding date in pandas DataFrame

Viewed 85

I have the following DataFrame with a Date column,

0      2021-12-13
1      2021-12-10
2      2021-12-09
3      2021-12-08
4      2021-12-07
          ...    
7990   1990-01-08
7991   1990-01-05
7992   1990-01-04
7993   1990-01-03
7994   1990-01-02

I am trying to find the index for a specific date in this DataFrame using the following code,

# import raw data into DataFrame
df = pd.DataFrame.from_records(data['dataset']['data'])
df.columns = data['dataset']['column_names']    
df['Date'] = pd.to_datetime(df['Date'])
# sample date to search for
sample_date = dt.date(2021,12,13)
print(sample_date)
# return index of sample date
date_index = df.index[df['Date'] == sample_date].tolist()
print(date_index)

The output of the program is,

2021-12-13
[]

I can't understand why. I have cast the Date column in the DataFrame to a DateTime and I'm doing a like-for-like comparison.

1 Answers

I have reproduced your Dataframe with minimal samples. By changing the way that you can compare the date will work like this below.

import pandas as pd
import datetime as dt
df = pd.DataFrame({'Date':['2021-12-13','2021-12-10','2021-12-09','2021-12-08']})
df['Date'] = pd.to_datetime(df['Date'].astype(str), format='%Y-%m-%d')
sample_date = dt.datetime.strptime('2021-12-13', '%Y-%m-%d')
date_index = df.index[df['Date'] == sample_date].tolist()
print(date_index)

output:

[0]

The search data was in the index number 0 of the DataFrame

Please let me know if this one has any issues

Related