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

标签 python pandas dataframe data-analysis

我想连接两个数据框。已经尝试过 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

关于如何做到这一点有什么建议吗?

最佳答案

让我们使用 mergesuffixesdrop:

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/

相关文章:

python - 你如何在 numpy 数组的每一行中广播 np.random.choice ?

python - 按主题搜索 PyPI

python - 如何在C/C++程序中加载内核模块

python - 创建NAN类别后,groupby对象的聚合出错

python - Pandas Dataframe 到嵌套 JSON

python - python 编码中的 mysql

python - 在 seaborn clustermap 上绘制

python pandas groupby 识别行

Python 数据帧 : replace or combine selected values into main DataFrame

python - 如何过滤属于超过 1 个成员的组的所有行?