Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

Expected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     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")
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading