我想连接两个数据框。已经尝试过 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
关于如何做到这一点有什么建议吗?
最佳答案
让我们使用 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
关于Python/Pandas - 合并基于非索引列的两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44768808/