0

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?

1
  • Please post code to initialze the dataframe so that we can work with and post working code. Commented Jul 5, 2021 at 20:08

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Daniel. I got my output using this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.