Python / Pandas - 合并基于非索引列的两个数据帧

abu*_*nte 4 python data-analysis dataframe pandas

我想加入两个数据框。已经尝试过 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
Run Code Online (Sandbox Code Playgroud)

我希望使用“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
Run Code Online (Sandbox Code Playgroud)

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

Sco*_*ton 5

让我们用mergesuffixesdrop

df1.merge(df2,  on='cnpj',suffixes=('','_y')).drop('index_y',axis=1)
Run Code Online (Sandbox Code Playgroud)

输出:

   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
Run Code Online (Sandbox Code Playgroud)