Pandas: How to aggregate a column and add the result as other columns?

Suppose I have a dataframe like:

   A  B 
0  1  1 
1  1  2 
2  2  3 
3  2  4 

I want to add min of B and max of B as new columns named minB and maxB.


     minB  maxB 
0  1  1    2 
2  2  3    4

I tried:

df.groupby('A').agg({'B':'min','B':'max'}).rename(columns={'B':'minB ','B':'maxB'})

However, it seems it can only apply one aggregate function and then I don’t know how to rename them to different columns even if it could apply two functions

>Solution :

Use Named Aggregation:

df.groupby("A", as_index=False).agg(
    minB=("B", "min"),
    maxB=("B", "max")

Leave a Reply