我有两个 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/