1

I have the following dataframe:

df[['ID','Team']].groupby(['Team']).agg([('total','count')]).reset_index("total").sort_values("count")

I basically, need to count the number of IDs by Team and then sort by the total number of IDs.

The aggregation part it's good and it gives me the expected result. But when I try the sort part I got this:

KeyError: 'Requested level (total) does not match index name (Team)'

What I am doing wrong?

1
  • Try this df[['ID','Team']].groupby(['Team']).agg([('total','count')]).reset_index().sort_values("count")
    – Synster
    Sep 17, 2020 at 11:27

1 Answer 1

2

Use names aggregation for specify new columns names in aggregate function, remove total from DataFrame.reset_index:

df = pd.DataFrame({
        'ID':list('abcdef'),
        'Team':list('aaabcb')
})

df = df.groupby('Team').agg(count=('ID','count')).reset_index().sort_values("count") 
print (df)
  Team  count
2    c      1
1    b      2
0    a      3

Your solution should be changed by specify column after groupby for processing, then specify new column name with aggregate function in tuple and last also remove total from reset_index:

df = df.groupby('Team')['ID'].agg([('count','count')]).reset_index().sort_values("count")
print (df)
  Team  count
2    c      1
1    b      2
0    a      3
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.