Home > Net >  Compare timestamps in two different DataFrames with different length and then merge them
Compare timestamps in two different DataFrames with different length and then merge them

Time:01-11

I have two Dataframes:

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  

I want to check whether df2['date'] is in df1['date']. I manage to do that by using the following: df2['date'].isin(df1['date']).all().

After that I want to create a new Dataframe that joins (probably with the use of df1.join(df2)) df1 and df2 and looks like this:

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

CodePudding user response:

Use DataFrame.merge and DataFrame.fillna

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

CodePudding user response:

Try this:

df_new = pd.merge(df1, df2, on='date', how='left')
  • Related