【问题标题】:how to merge two dataframe with different times and sizes如何合并两个具有不同时间和大小的数据框
【发布时间】:2023-02-04 03:23:43
【问题描述】:

我正在尝试将这两个数据框合并在一起并保留所有行和列。它们在“时间”列下有不同的时间,所以我希望它们以时间顺序的方式合并。

df1:

time run_id weight
0 H1 500
24 H1 400
48 H1 300
0 H2 900
24 H2 800
48 H2 700

df2:

time run_id totalizer
0.5 H1 100
10 H1 200
40 H1 300
60 H1 400
0.5 H2 900
5 H2 1000
35 H2 1100
70 H2 1200

我如何将这两个表合并为:

time run_id weight totalizer
0 H1 500
0.5 H1 100
10 H1 200
24 H1 400
40 H1 300
48 H1 300
60 H1 400
0 H2 900
0.5 H2 900
5 H2 1000
24 H2 800
35 H2 1100
48 H2 700
70 H2 1200

我试过了

mergedf = df1.merge(df2, how='outer')

但它将 df1 堆叠在 df2 之上。

感谢任何帮助,谢谢!

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    一种选择是使用 combine_first

    cols = ["run_id", "time"]
    ​
    out = (
            df1.set_index(cols)
                  .combine_first(df2.set_index(cols))
                  .reset_index().sort_values(by=cols)
               [["time", "run_id", "weight", "totalizer"]]
           )
    

    输出:

    print(out)
    
        time run_id  weight  totalizer
    0    0.0     H1   500.0        NaN
    1    0.5     H1     NaN      100.0
    2   10.0     H1     NaN      200.0
    3   24.0     H1   400.0        NaN
    4   40.0     H1     NaN      300.0
    5   48.0     H1   300.0        NaN
    6   60.0     H1     NaN      400.0
    7    0.0     H2   900.0        NaN
    8    0.5     H2     NaN      900.0
    9    5.0     H2     NaN     1000.0
    10  24.0     H2   800.0        NaN
    11  35.0     H2     NaN     1100.0
    12  48.0     H2   700.0        NaN
    13  70.0     H2     NaN     1200.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2021-09-05
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多