Reputation: 31
I need to compare two date-time columns in a dataframe and create a new column that returns a 0/1 flag.
Dataframe:
+-------------------+-------------------+
| Date1 | Date2 |
+-------------------+-------------------+
| 6-8-2020 13:27:01 | 6-8-2020 13:14:04 |
| 6-8-2020 5:01:02 | 7-8-2020 8:00:25 |
| 6-8-2020 7:45:43 | 6-8-2020 8:10:04 |
+-------------------+-------------------+
The condition is: if date1 > date2 then 1 else 0
Wanted result from the example dataframe above:
+------+
| Flag |
+------+
| 1 |
| 0 |
| 0 |
+------+
Can someone help me with this?
Upvotes: 1
Views: 1747
Reputation: 862511
Convert values to datetimes first, compare and convert True, False
values to 1, 0
by Series.astype
:
df.Date1 = pd.to_datetime(df.Date1, dayfirst=True)
df.Date2 = pd.to_datetime(df.Date2, dayfirst=True)
df['Flag'] = (df.Date1 > df.Date2).astype(int)
print (df)
Date1 Date2 Flag
0 2020-08-06 13:27:01 2020-08-06 13:14:04 1
1 2020-08-06 05:01:02 2020-08-07 08:00:25 0
2 2020-08-06 07:45:43 2020-08-06 08:10:04 0
Or use for compare Series.gt
and for 1,0
Series.view
:
df['Flag'] = df.Date1.gt(df.Date2).view('i1')
Upvotes: 1