python - 如何连接两个pandas数据框

标签 python python-2.7 pandas dataframe

我有两个 pandas 数据框:

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

现在我想根据字段frid合并这两个数据框。换句话说,我想将 comment 列添加到 df1 中。我怎样才能做到这一点?我知道 join 命令,但它的工作方式不同 (df1.join(df2))。

结果应该是:

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

最佳答案

使用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

关于python - 如何连接两个pandas数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910759/

相关文章:

python - 如何在python中正确打开文件并打印出文本内容

Python - 将参数从一个函数传递给嵌套函数调用

python - 重复行以获取所有星期的数据

python - super() 对象的动态方法解析

python - 在 Pandas Groupby 和 Agg 中保留一列但使用其他列

Django:从 Pandas 到 Django Rest Framework 的模型查询集

python - 通过pycharm运行google app engine django项目时导入错误

Python - 删除非字母数字字符但保留空格和西类牙语/葡萄牙语字符

python - QTranslator 如何处理语言环境修饰符 PyQT?

python-3.x - pandas pivot 转换 DataFrame