Jed
Jed

Reputation: 399

How do I create a new column in my dataframe based on a date condition, within Python?

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))

Upvotes: 0

Views: 104

Answers (1)

mozway
mozway

Reputation: 260300

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))

Upvotes: 1

Related Questions