how to join and sum columns (of different lengths) in pandas?

Question:

lets say I have the following dataframes

df1

name  value 
a      3   
b      4
c      5

df2

name  value 
b      2  
a      1

and I want to make a dataframe like this (there can be many value columns)

name  value 
a      4   
b      6
c      5

Does anyone know how I would do this?

Asked By: Dylan

||

Answers:

You can temporarily set "name" as index:

df1.set_index('name').add(df2.set_index('name'), fill_value=0).reset_index()

Output:

  name  value
0    a    4.0
1    b    6.0
2    c    5.0
Answered By: mozway
df2.set_index("name").reindex(df1.name).fillna(0).astype(int)+df1.set_index("name")

out:

      value
name       
a         4
b         6
c         5
Answered By: G.G
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.