I want to sort a pandas dataframe by count of a value in a column. For values with the same count, I want them clustered, and sorted alphabetically.
I tried different settings with the sort
call. I also tried first sorting the dataframe alphabetically, and next by count.
Here's the relevant section of the code I currently use:
import pandas as pd
df = pd.read_csv("filename.csv")
df['Counts'] = df.groupby(['Words']).transform('count')
df.sort_values('Counts', inplace=True, ascending=False)
print(df)
What I get is something like:
Words Counts 1 Alpha 2 2 Beta 2 3 Charlie 2 4 Alpha 2 5 Beta 2 6 Charlie 2 7 Delta 1
What I want is:
Words Counts 1 Alpha 2 2 Alpha 2 3 Beta 2 4 Beta 2 5 Charlie 2 6 Charlie 2 7 Delta 1
Thank you for your help!