【问题标题】:how to merge two DF with different columns? [duplicate]如何将两个 DF 与不同的列合并? [复制]
【发布时间】:2022-01-05 02:47:48
【问题描述】:

我有这两个数据框 df1 - 有 5 行

|id|name|age|weight|
|1 |aaaa|16 | 56   |
|2 |bbbb|17 | 60   |
|3 |cccc|18 | 56   |
|4 |dddd|16 | 61   |
|5 |ffff|20 | 75   |

df2 - 也有 5 行 id 相同但未排序

|id|rate|
|5 |0.75|
|1 |0.80|
|3 |0.92|
|4 |0.86|
|2 |0.77|

现在我需要将它们合并成这样 df3

|id|name|age|weight|rate|
|1 |aaaa|16 | 56   |0.80|
|2 |bbbb|17 | 60   |0.77|
|3 |cccc|18 | 56   |0.92|
|4 |dddd|16 | 61   |0.86|
|5 |ffff|20 | 75   |0.75|

提前致谢

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

使用merge:

>>> df1.merge(df2, on='id')
   id  name  age  weight  rate
0   1  aaaa   16      56  0.80
1   2  bbbb   17      60  0.77
2   3  cccc   18      56  0.92
3   4  dddd   16      61  0.86
4   5  ffff   20      75  0.75

阅读Pandas Merging 101

【讨论】:

    【解决方案2】:

    我建议您使用 pandas 的合并功能。它允许您指定要在两个数据帧上执行的连接类型。

    pd.merge(left = first_dataframe, right = second_dataframe, how = 'specify the type of join here like left, right, inner etc..', on = 'specify the column here')
    

    这里有一些文档可用于引用合并功能。 https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html

    【讨论】:

      【解决方案3】:

      如果你有一个类似这样的 df_1:

         id name  col1
      0   1  foo    42
      1   2  bar    43
      

      和df_2类似:

         id  rate
      0   2    -1
      1   1     1
      

      您可以使用 pandas (doc) 中的 join 方法:

      df_1.join(df_2.set_index("id"), on="id") 这给出了

         id name  col1  rate
      0   1  foo    42     1
      1   2  bar    43    -1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 2015-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多