Reputation: 61
I have a python code in which I need to compare entered date with existing pandas Date column and get index number of that rows. But if that date doesn't exist then it should get index number of rows of exact previous dates. Example of code and dataframe is given below.
Dataframe:-
SR.No Date
1 01-12-2013
1 01-12-2014
1 01-12-2015
1 01-12-2016
1 01-12-2017
1 01-12-2018
1 01-12-2019
1 01-12-2020
1 01-12-2013
1 01-12-2014
1 01-12-2015
1 01-12-2016
1 01-12-2017
1 01-12-2018
1 01-12-2019
1 01-12-2020
2 01-12-2013
2 01-12-2014
2 01-12-2015
2 01-12-2016
2 01-12-2017
2 01-12-2018
2 01-12-2019
2 01-12-2020
2 01-12-2013
2 01-12-2014
2 01-12-2015
2 01-12-2016
2 01-12-2017
2 01-12-2018
2 01-12-2019
2 01-12-2020
Code:-
date = '01-06-2018'
df['Date'] = pd.to_datetime(df['Date'],dayfirst=True)
date = pd.to_datetime(date,dayfirst=True)
if df['Date'].eq(date).any():
_index = df[df['Date'].eq(date)].index
else:
date = (date - pd.DateOffset(months=6))
_index = df[df['Date'].eq(date)].index
But in case we change input date from '01-06-2018'
to '01-09-2018'
or '01-03-2018'
. Then it also should become only 01-12-2017 using DateOffset(months=3)
and DateOffset(months=9)
respectively and should get me the index number of 01-12-2017.
So how can we do that using if elif else conditions? Or using any other way?
Upvotes: 0
Views: 664
Reputation: 42778
You have to find the largest date less than the given date:
date = df[df['Date'] <= date]['Date'].max()
index = df[df['Date'] == date].index
Upvotes: 1