Andrew Lim
Andrew Lim

Reputation: 33

If statement for when a date is within a date range

I am creating a flag that generates 1 when condition is satisfied, else 0

I am trying to get to this state

enter image description here

I want to create a code that if df['Won'] = 1 or '2018-10-31' < df['Created Date'] < '2018-12-01' then it will return 1, else 0

Currently my code is:

df['Deal'] = pd.np.where((df['Won'] == 1) | (df['Created Date']>'2018-10-31'), 1, 0) 

I am not sure how to fix my code

Thanks in advance!

Upvotes: 0

Views: 4465

Answers (1)

n3utrino
n3utrino

Reputation: 1210

df['Deal'] = (df['Won'] == 1) | ( (df['Created Date']>'2018-10-31') & (df['Created Date']<'2018-12-01') )

This will return a bool, which you can convert to an int if you'd like, with an astype(int) command. Also, I'd recommend converting those date strings to actual datetime objects with something like

df['Created Date'] = pd.to_datetime(df['Created Date'])

then your df['Deal'] query would have something more like

df['Created Date'] > dt.datetime(2018,10,31).

Upvotes: 2

Related Questions