繁体   English   中英

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

[英]Compare timestamps in two different DataFrames with different length and then merge them

我有两个数据框:

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})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM