0

I have a data frame df

df=pd.DataFrame({"city" : ['mum','ban','mum','mum','ban','mum','ban'],
                      "id":[1,1,2,1,3,4,1],
                      "money_have":[100,125,101,900,89,97,78]})

I want to get the top 2 ids of each group having money

I know to group by like this

df.groupby(['city','id']).agg({'money_have':'sum'})

but don't know to select topn from each group

Expected output

df=pd.DataFrame({"city" : ['ban','ban','mum','mum'],
                      "id":[1,3,1,2],
                      "money_have":[203,89,1000,101]})
Amit
  • 691
  • 4
  • 12

0 Answers0