Python 基于时间戳合并数据帧
有两个这样的数据帧(示例) df1 df2 然后,我想加入df1和df2,但我不知道怎么做,因为在第二个df中,我只有开始和结束时间。如何根据第二个df的数据对第一个df设置条件 这就是我想要的Python 基于时间戳合并数据帧,python,pandas,dataframe,datetime,join,Python,Pandas,Dataframe,Datetime,Join,有两个这样的数据帧(示例) df1 df2 然后,我想加入df1和df2,但我不知道怎么做,因为在第二个df中,我只有开始和结束时间。如何根据第二个df的数据对第一个df设置条件 这就是我想要的 Data Value Condition 0 2020-01-31 10:30:00 3 OK 1 2020-01-31 11:30:00 4 BAD 2 2020-01-31 12:30:00 1
Data Value Condition
0 2020-01-31 10:30:00 3 OK
1 2020-01-31 11:30:00 4 BAD
2 2020-01-31 12:30:00 19 BAD
3 2020-01-31 13:30:00 22 BAD
4 2020-01-31 14:30:00 4 OK
5 2020-01-31 15:30:00 5 ERROR
6 2020-01-31 15:30:00 6 ERROR
7 2020-01-31 16:30:00 7 OK
8 2020-01-31 17:30:00 9 OK
9 2020-01-31 18:30:00 7 OK
10 2020-01-31 19:30:00 8 OK
尝试将pd.merge\u asof:
# make sure that `Data`, `DSTART`, `DEnd` are datetime type
# use `pd.to_datetime` if needed
tmp = pd.merge_asof(df1,df2, left_on='Data', right_on='DSTART')
df1['Condition'] = tmp['Condition'].where(tmp['Data'] <= tmp['DEnd'], 'OK')
@Quanq我试着这样做:tmp=pd.merge\u asof('u dadosPIMS,'u dadosMan,left'u on='Data',right'u on='Inicio Real'))\u dadosPIMS['Falha']=tmp['Falha']=tmp['Data']@VitorFernandes Sort
df1
byData
,df2
byDSTART
:df1=df1.Sort\u值('Data')
(您的样本数据帧已经排序)。您需要小心索引。两个数据框合并。这项工作用于合并工业数据和维护数据的数据框,我将df导出到excel,但我发现了一个问题。2020年10月26日07:00至2021年10月26日,我们进行了维护。结果的数据框向我显示,此维护发生在2021年10月27日和2021年10月28日之间21.我发现了更多这样的例子。在我写的代码中:#u-dadosMan['Inicio-Real']=pd.to-datetime(#u-dadosMan['Inicio-Real'])#u-dadosMan['Fim-Real']=pd.to-datetime(#u-dadosm['Data']),然后我像你说的那样使用:#u-dadosm to-datetime(#dadosMan['Data'.'sort'])_dadosMan=_dadosMan.sort_values('Inicio Real')######tmp=pd.merge_asof(_dadosMan,_dadosMan,left_on='Data',right_on='Inicio Real')_dadosPIMS['Falha']=tmp['Falha'])。其中((tmp['Data']>tmp['Inicio Real'])和(tmp['Data']
Data Value Condition
0 2020-01-31 10:30:00 3 OK
1 2020-01-31 11:30:00 4 BAD
2 2020-01-31 12:30:00 19 BAD
3 2020-01-31 13:30:00 22 BAD
4 2020-01-31 14:30:00 4 OK
5 2020-01-31 15:30:00 5 ERROR
6 2020-01-31 15:30:00 6 ERROR
7 2020-01-31 16:30:00 7 OK
8 2020-01-31 17:30:00 9 OK
9 2020-01-31 18:30:00 7 OK
10 2020-01-31 19:30:00 8 OK
# make sure that `Data`, `DSTART`, `DEnd` are datetime type
# use `pd.to_datetime` if needed
tmp = pd.merge_asof(df1,df2, left_on='Data', right_on='DSTART')
df1['Condition'] = tmp['Condition'].where(tmp['Data'] <= tmp['DEnd'], 'OK')
Data Value Condition
0 2020-01-31 10:30:00 3 OK
1 2020-01-31 11:30:00 4 BAD
2 2020-01-31 12:30:00 19 BAD
3 2020-01-31 13:30:00 22 OK
4 2020-01-31 14:30:00 4 OK
5 2020-01-31 15:30:00 5 ERROR
6 2020-01-31 15:30:00 6 ERROR
7 2020-01-31 16:30:00 7 ERROR
8 2020-01-31 17:30:00 9 OK
9 2020-01-31 18:30:00 7 OK
10 2020-01-31 19:30:00 8 OK