emax
emax

Reputation: 7235

Pandas: merge two dataframes and make the average over one column

I have two dataframes:

df1
      id    val
0    Tom     5
1    Alex    3
2    Sarah   2
3    Julia   7


df1
      id    val
0    Tom     2
1    Alex    1
2    Bob     2

I would like to have a dataframe like the following

df1
      id    val
0    Tom    3.5
1    Alex    2
2    Sarah   2
3    Julia   7
4    Bob     2

Upvotes: 1

Views: 720

Answers (1)

anky
anky

Reputation: 75080

You can concat + groupby:

pd.concat((df1,df2)).groupby('id',as_index=False,sort=False)['val'].mean()

      id  val
0    Tom  3.5
1   Alex  2.0
2  Sarah  2.0
3  Julia  7.0
4    Bob  2.0

Upvotes: 4

Related Questions