Sort column in Dataframe alphabetically after GroupBy

Viewed 189

I have used GroupBy to sum the 'Amount' in the dataframe data_2020 .

data_2020.groupby(['Category'])['Amount'].sum().sort_values(ascending=False)

data_2020

Now, I want to sort by the column 'Category'. I have tried to use sort_values(by=['Category'], inplace=True) but now I am getting an error message :

TypeError: sort_values() got an unexpected keyword argument 'by'

How I can sort by column 'Category'?

1 Answers

This statement

data_2020.groupby(['Category'])['Amount'].sum().sort_values(ascending=False)

will return a pandas Series.

>>> import pandas as pd
>>> 
>>> 
>>> lst = [28793.78, 6380.09, 5895.26, 324.79, 279.76, 239.62]
>>> categories = ['0', 'Amazon', 'Supermarker', 'Taxi', 'Newspapers', 'Boots']
>>> ser = pd.Series(lst, index=categories)
>>> ser.index.name = 'Category'
>>> ser
Category
0              28793.78
Amazon          6380.09
Supermarker     5895.26
Taxi             324.79
Newspapers       279.76
Boots            239.62
dtype: float64

pandas.Series.sort_values doesn't accept by argument (in contrast to pandas.DataFrame.sort_values which does).


sort_index(ascending=True) should do the trick:

>>> ser.sort_index(ascending=True)
Category
0              28793.78
Amazon          6380.09
Boots            239.62
Newspapers       279.76
Supermarker     5895.26
Taxi             324.79
dtype: float64
Related