Ahmad
Ahmad

Reputation: 9658

Pandas: How to aggregate a column with multiple functions and add the results 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

   A  minB maxB 
0  1  1    2 
1  2  3    4

Upvotes: 2

Views: 44

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34066

Use numpy.min & numpy.max:

In [472]: import numpy as np

In [473]: df.groupby('A').agg({'B':[np.min, np.max]}).reset_index()
Out[473]: 
   A    B     
     amin amax
0  1    1    2
1  2    3    4

Upvotes: 1

Code Different
Code Different

Reputation: 93171

Use Named Aggregation:

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

Upvotes: 1

Related Questions