【问题标题】:Merge or concat two df by index按索引合并或连接两个 df
【发布时间】:2022-07-28 16:05:53
【问题描述】:

我有以下问题:我想连接或合并两个具有不同长度和部分不同索引的数据帧:

数据1:

index data1
1 16
2 37
3 18
7 49

数据2:

index data2
2 74
3 86
4 12
6 97
12 35

它们应该以这样的方式合并,输出看起来像:

index data1 data2
1 16 NaN
2 37 74
3 18 86
4 NaN 12
6 NaN 97
7 49 NaN
12 NaN 35

希望你能帮帮我。

提前致谢

【问题讨论】:

    标签: python pandas merge concatenation


    【解决方案1】:

    你可以使用join:

    out = df1.join(df2, how='outer')
    print(out)
    
    # Output
           data1  data2
    index              
    1       16.0    NaN
    2       37.0   74.0
    3       18.0   86.0
    4        NaN   12.0
    6        NaN   97.0
    7       49.0    NaN
    12       NaN   35.0
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2019-04-03
      • 2012-03-21
      • 2019-12-13
      • 2011-01-18
      • 2017-03-20
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多