【问题标题】:Compare timestamps in two different DataFrames with different length and then merge them比较两个不同长度的不同数据帧中的时间戳,然后合并它们
【发布时间】:2023-01-11 02:32:18
【问题描述】:

我有两个数据框:

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

【问题讨论】:

    标签: python pandas dataframe join merge


    【解决方案1】:

    使用DataFrame.mergeDataFrame.fillna

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

    【讨论】:

    • on='date',不是on'date' :)
    • 随意编辑:) @BrokenBenchmark
    猜你喜欢
    • 2019-02-27
    • 2021-01-09
    • 2017-06-03
    • 2019-11-19
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2012-12-15
    相关资源
    最近更新 更多