Getting a Key Error = 'sum' when using groupby and aggregate (sum)

Viewed 29

I wanted to sort the DataFrame by sum, in descending order

DataFrame

I use the following code:

new_df = df.groupby(
  ['Category'])[['Total']].agg(
  ['sum', 'mean', 'count']).sort_values(
  'sum', ascending=False).copy()

and it gives me the following error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_557/4086857446.py in <module>
      4 
      5 sector.head()
----> 6 sector = data.sort_values('sum', ascending=False)

/usr/local/lib/python3.7/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    309                     stacklevel=stacklevel,
    310                 )
--> 311             return func(*args, **kwargs)
    312 
    313         return wrapper

/usr/local/lib/python3.7/site-packages/pandas/core/frame.py in sort_values(self, by, axis, ascending, inplace, kind, na_position, ignore_index, key)
   6257 
   6258             by = by[0]
-> 6259             k = self._get_label_or_level_values(by, axis=axis)
   6260 
   6261             # need to rewrap column in Series to apply key function

/usr/local/lib/python3.7/site-packages/pandas/core/generic.py in _get_label_or_level_values(self, key, axis)
   1777             values = self.axes[axis].get_level_values(key)._values
   1778         else:
-> 1779             raise KeyError(key)
   1780 
   1781         # Check for duplicates

KeyError: 'sum'

What have I done wrong?

1 Answers

You need to include the .reset_index() method The below should work.

new_df = df.groupby(
  ['Category'])[['Total']].agg(
  ['sum', 'mean', 'count']).reset_index().sort_values(
  'sum', ascending=False).copy()

Related