【问题标题】:Python / Pandas - merging two dataframes based in a non-index columnPython / Pandas - 合并基于非索引列的两个数据框
【发布时间】:2017-06-26 21:15:49
【问题描述】:

我想加入两个数据框。已经尝试过 concat、merge 和 join,但我应该做错了什么。

df 1:

index    cnpj   country   state
1        7468        34      23   
4        3421        23      12
7        2314        12      45


df 2:

index    cnpj    street  number
2        7468        32      34   
5        3421        18      89
546      2314        92      73

我希望使用“cnpj”作为“连接键”将它们合并,并保留 df1 的索引。它应该是这样的:

df 1:

index    cnpj   country   state    street  number
1        7468        34      23        32      34      
4        3421        23      12        18      89
7        2314        12      45        92      73

关于如何做到这一点的任何建议?

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    让我们将merge 与suffixes 和drop 一起使用:

    df1.merge(df2,  on='cnpj',suffixes=('','_y')).drop('index_y',axis=1)
    

    输出:

       index  cnpj  country  state  street  number
    0      1  7468       34     23      32      34
    1      4  3421       23     12      18      89
    2      7  2314       12     45      92      73
    

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多