Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

python - Pandas DataFrame merge summing column

I'm trying to merge two DataFrames summing columns value.

>>> print(df1)
   id name  weight
0   1    A       0
1   2    B      10
2   3    C      10

>>> print(df2)
   id name  weight
0   2    B      15
1   3    C      10

I need to sum weight values during merging for similar values in the common column.

merge = pd.merge(df1, df2, how='inner')

So the output will be something like following.

   id name  weight
1   2    B      25
2   3    C      20
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This solution works also if you want to sum more than one column. Assume data frames

>>> df1
   id name  weight  height
0   1    A       0       5
1   2    B      10      10
2   3    C      10      15
>>> df2
   id name  weight  height
0   2    B      25      20
1   3    C      20      30

You can concatenate them and group by index columns.

>>> pd.concat([df1, df2]).groupby(['id', 'name']).sum().reset_index()
   id name  weight  height
0   1    A       0       5
1   2    B      35      30
2   3    C      30      45

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...