简体   繁体   English

如何连接两个熊猫数据框

[英]How to join two pandas data frames

I have two pandas data frames: 我有两个熊猫数据框:

df1
    id frid title
    1  1    abc
    2  1    ddd
    3  2    ghc
    4  3    frg
    5  1    def

df2
    frid comment
    1    w
    2    s
    3    e

Now I want to merge these two data frames based on the field frid . 现在,我想基于字段frid合并这两个数据帧。 In other words, I want to add column comment to df1 . 换句话说,我想向df1添加列comment How can I do this? 我怎样才能做到这一点? I know about join command, but it works differently ( df1.join(df2) ). 我知道join命令,但是它的工作方式不同( df1.join(df2) )。

The result should be: 结果应为:

df
    id frid title comment
    1  1    abc   w
    2  1    ddd   w
    3  2    ghc   s
    4  3    frg   e
    5  1    def   w

use merge and pass the column you want to merge on, by default this performs an 'inner' merge: 使用merge并传递要合并的列,默认情况下会执行“内部”合并:

In [198]:
df1.merge(df2, on='frid')

Out[198]:
   id  frid title comment
0   1     1   abc       w
1   2     1   ddd       w
2   5     1   def       w
3   3     2   ghc       s
4   4     3   frg       e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM