Home > Back-end >  How do I create a new column in my dataframe based on a date condition, within Python?
How do I create a new column in my dataframe based on a date condition, within Python?

Time:11-08

enter image description here

How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the '(Declined - Reason) Or Hire' column starts with "Offer Declined -..." and the 'Date' column is between January and March 2022. I started with the code below, which works for my first condition, but not sure how to add the date condition to it.

df['Declined Or Hired'] = (df[''(Declined - Reason) Or Hire'].str.startswith('Offer Declined', na = False ).astype(int))

CodePudding user response:

Use a second condition:

df['Declined Or Hired'] = (df['(Declined - Reason) Or Hire'].str.startswith('Offer Declined',  na=False)
                           & pd.to_datetime(df['Date'], dayfirst=True)
                               .between(pd.Timestamp('2022-01-01'), pd.Timestamp('2022-03-31'))
                           ).astype(int))
  • Related