unable to fetch row where index is of type dtype='datetime64[ns]'

Viewed 45

I have a pandas main_df dataframe with date as index

<bound method Index.get_value of DatetimeIndex(['2021-05-11', '2021-05-12','2021-05-13'],
 dtype='datetime64[ns]', name='date', freq=None)>

what am trying to do is fetch row based on certain date.

I tried like this main_df.loc['2021-05-11'] and it works fine.

But If I pass a date object its failing

main_df.loc[datetime.date(2021, 5, 12)] and its showing key error.

The index is DatetimeIndex then why its throwing an error if I didn't pass key as string?

1 Answers

Reason is DatetimeIndex is simplified array of datetimes, so if select vy dates it failed.

So need select by datetimes:

main_df = pd.DataFrame({'a':range(3)}, 
                        index=pd.to_datetime(['2021-05-11', '2021-05-12','2021-05-13']))
print (main_df)
            a
2021-05-11  0
2021-05-12  1
2021-05-13  2

print (main_df.index)
DatetimeIndex(['2021-05-11', '2021-05-12', '2021-05-13'], dtype='datetime64[ns]', freq=None)

print (main_df.loc[datetime.datetime(2021, 5, 12)])
a    1
Name: 2021-05-12 00:00:00, dtype: int64

If need select by dates first convert datetimes to dates by DatetimeIndex.date:

main_df.index = main_df.index.date
print (main_df.index)
Index([2021-05-11, 2021-05-12, 2021-05-13], dtype='object')

print (main_df.loc[datetime.date(2021, 5, 12)])
a    1
Name: 2021-05-12, dtype: int64

If use string it use exact indexing, so pandas select in DatetimeIndex correct way.

Related