Python 比较数据帧中的两个datetime列并返回标志
我需要比较数据帧中的两个日期时间列,并创建一个返回0/1标志的新列 数据帧:Python 比较数据帧中的两个datetime列并返回标志,python,pandas,dataframe,Python,Pandas,Dataframe,我需要比较数据帧中的两个日期时间列,并创建一个返回0/1标志的新列 数据帧: +-------------------+-------------------+ | 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 | |
+-------------------+-------------------+
| 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 |
+-------------------+-------------------+
条件是:如果date1>date2,则为1,否则为0
上述示例数据帧的所需结果:
+------+
| Flag |
+------+
| 1 |
| 0 |
| 0 |
+------+
有人能帮我吗?首先将值转换为日期时间,比较
True、False
值并将其转换为1,0
:
或用于比较和1,0
:
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
df['Flag'] = df.Date1.gt(df.Date2).view('i1')