close

How can I “merge” rows by same value in a column in Pandas with aggregation functions?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I “merge” rows by same value in a column in Pandas with aggregation functions in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How can I “merge” rows by same value in a column in Pandas with aggregation functions?

  1. How can I “merge” rows by same value in a column in Pandas with aggregation functions?

    You are looking for
    aggregation_functions = {'price': 'sum', 'amount': 'sum', 'name': 'first'} df_new = df.groupby(df['id']).aggregate(aggregation_functions)

  2. “merge” rows by same value in a column in Pandas with aggregation functions

    You are looking for
    aggregation_functions = {'price': 'sum', 'amount': 'sum', 'name': 'first'} df_new = df.groupby(df['id']).aggregate(aggregation_functions)

Method 1

You are looking for

aggregation_functions = {'price': 'sum', 'amount': 'sum', 'name': 'first'}
df_new = df.groupby(df['id']).aggregate(aggregation_functions)

which gives

    price     name  amount
id                        
1     130     anna       3
2      42      bob      30
3       3  charlie     110

Method 2

For same columns ordering is necessary add reindex, because aggregate by dict:

d = {'price': 'sum', 'name': 'first', 'amount': 'sum'}
df_new = df.groupby('id', as_index=False).aggregate(d).reindex(columns=df.columns)
print (df_new)
   amount  id     name  price
0       3   1     anna    130
1      30   2      bob     42
2     110   3  charlie      3

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read