Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas value_counts( ) not in descending order

Tags:

python

pandas

There is a dataframe,df

Index              Date               Name         Category
 0            2017-08-09              ABC-SAP       1
 1            2017-08-09              CDE-WAS       2
 2            2017-08-10              DEF           3
 3            2017-08-11              DEF           3
 4            2017-08-11              CDE-WAS       2
 5            2017-08-11              CDE-WAS       2

I executed this code:

df2=pd.DataFrame(df, columns= ['Name','Category'])
df2= df['Name'].groupby(df['Category']).value_counts()
print(df2)

Then I get:

 Index             Name
 (1,ABC-SAP)       1              
 (2,CDE-WAS)       3                         
 (3,DEF)           2             

The value.counts( ) does not return a descending order on the NAME column. I really want to have it in descending order from highest to lowest count. Any way of doing it?

like image 921
Bode Avatar asked Dec 20 '17 06:12

Bode


1 Answers

For me it working nice, but you can test alternative solution:

df2 = df['Name'].groupby(df['Category']).value_counts()
print(df2)
Category  Name   
Pri       CDE-WAS    3
          DEF        2
          ABC-SAP    1
Name: Name, dtype: int64


df2 = df.groupby('Category')['Name'].value_counts()
print(df2)
Category  Name   
Pri       CDE-WAS    3
          DEF        2
          ABC-SAP    1
Name: Name, dtype: int64

EDIT:

For sort all values use sort_values:

df1 = df.groupby('Category')['Name'].value_counts().sort_values(as‌​cending=False)
like image 177
jezrael Avatar answered Nov 03 '22 23:11

jezrael