Group by and apply sum, divide , round functions to a single column along with aggregators on other column

Viewed 87

I have a dataframe like this

df1 = pd.DataFrame([['a',1,100],['b',2,300],['c',3,400]],columns = ['col1','col2','col3'])

Required output

summary_df = df1.groupby('col1').agg({'col2':'sum','col3':'sum'}).reset_index() #line1
summary_df['col3'] = round(summary_df['col3']/1000,2)

Can we do the division and rounding function in the line1 itself. I have more columns to do like that. So adding a line for each column is not a good idea.

2 Answers

You can also pass a lambda function as aggregate, and perform column specific functions for a particular column.

>>> df1.groupby('col1').agg({'col2':'sum','col3':lambda x:round(x.sum()/1000,2)})

      col2  col3
col1            
a        1   0.1
b        2   0.3
c        3   0.4

If you need to apply the same function more than once, its better to create a normal function, and use it for multiple columns, instead of using lambda:

def func(x):
    return round(x.sum()/1000,2)

df1.groupby('col1').agg({'col2':'sum','col3':func})
      col2  col3
col1            
a        1   0.1
b        2   0.3
c        3   0.4

Yes you can do that using assign.

summary_df = (df1.groupby('col1')  
              .agg({'col2':'sum','col3':'sum'})  
              .reset_index()  
              .assign(col3=lambda x: round(x['col3']/1000,2))) #line1  
Related