比较两个不同长度的dataframe中的时间戳,然后合并它们



我有两个dataframe:

df1=
date                col1 col2
0  2023-01-01 16:00:00 100  200
1  2023-01-01 16:15:00 120  400
2  2023-01-01 16:30:00 140  500
3  2023-01-01 16:45:00 160  700
4  2023-01-01 17:00:00 200  300
5  2023-01-01 17:15:00 430  200
6  2023-01-01 17:30:00 890  100
df2 =
date                col3 
0  2023-01-01 16:00:00 1  
1  2023-01-01 16:15:00 1  
2  2023-01-01 17:00:00 1  

我想检查df2['date']是否在df1['date']中。我设法做到这一点,使用以下:df2['date'].isin(df1['date']).all().

之后,我想创建一个新的Dataframe,连接(可能使用df1.join(df2))df1df2,看起来像这样:

df_new=
date                col1 col2 col3
0  2023-01-01 16:00:00 100  200  1
1  2023-01-01 16:15:00 120  400  1
2  2023-01-01 16:30:00 140  500  0
3  2023-01-01 16:45:00 160  700  0
4  2023-01-01 17:00:00 200  300  1
5  2023-01-01 17:15:00 430  200  0
6  2023-01-01 17:30:00 890  100  0

使用DataFrame.mergeDataFrame.fillna

df_result = df.merge(df2, on='date', how='left').fillna({'col3':0})

最新更新