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
CodePudding user response:
Use Named Aggregation:
df.groupby("A", as_index=False).agg(
minB=("B", "min"),
maxB=("B", "max")
)
CodePudding user response:
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