合并两个不同长度+总和公用值的python pandas 数据帧 [英] Merge two python pandas data frames of different length + sum common values

查看:97
本文介绍了合并两个不同长度+总和公用值的python pandas 数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:我有两个不同长度的pandas数据帧,其中包含一些具有共同值的行,而某些行则像这样不同:

I have the following problem: I have two pandas data frames of different length containing some rows that have common values and some that are different like this:

df1

     s1  s2  s3  s4
sp1   1   0   1   1
sp2   1   1   0   1
sp3   1   1   1   0
sp4   1   1   1   1

df2

     s1  s2  s3  s4
sp1   1   0   1   1
sp3   1   1   1   0
sp5   1   1   1   1

我想将两个表合并为以下结果:

I would like to merge the two tables with the following result:

     s1  s2  s3  s4
sp1   2   0   2   2
sp2   1   1   0   1
sp3   2   2   2   0
sp4   1   1   1   1
sp5   1   1   1   1

是否可以合并两个数据框并添加公共单元格?

Is that possible to merge the two dataframe and make the addition of the common cells?

推荐答案

解决方案

df1.add(df2, fill_value=0)

df1.add(df2, fill_value=0).astype(int)

这完全可以使用要解决此确切问题的参数来完成您想要的操作.我在末尾添加了astype(int)来保存int

This does exactly what you want using arguments intended to solve this exact problem. I added astype(int) at the end to preserve int

这篇关于合并两个不同长度+总和公用值的python pandas 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆