Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe Groupby with Min,Max and Sum

I have the following dataframe at AID level and I would like to Group By on CID with min priority, max Ind values and also calculate the sum for amount field

Dataframe

AID   CID   priority amount    Ind
100   C100     1       50       1
200   C100     2       100      0
300   C300     5       300      0
400   C300     3       200      0
500   C300     4       150      0

Desired Dataframe

CID  Priority   amount   Ind
C100    1       150       1
C300    3       650       0

I tried this

df2=df.groupby(['CID']).min('Priority')

Error: method object is not subscriptable
like image 239
ckp Avatar asked Sep 05 '25 03:09

ckp


1 Answers

print(
    df.groupby("CID", as_index=False).agg(
        {"priority": "min", "Ind": "max", "amount": "sum"}
    )
)

Prints:

    CID  priority  Ind  amount
0  C100         1    1     150
1  C300         3    0     650
like image 106
Andrej Kesely Avatar answered Sep 09 '25 06:09

Andrej Kesely