Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Sorting pivoted columns in pd.pivot_table

$
0
0

I have a dataframe of the kind:original dataframe

I intend to pivot it so that the 3 types of medals become the columns and their respective counts and mean scores become the value. Like this:pivot_table

Although, I want the columns of the pivot table in the order : 'Gold', 'Silver', 'Bronze' instead of the alphabetic order that it is currently getting displayed in.

I have tried this :df['medals']=pd.Categorical(values = df['medals'], ordered = True, categories =['Gold','Silver','Bronze'])

df = df.sort_values(by =[ 'name','medals'])

This resulted in my original dataframe's rows being in the expected order :original dataframe after custom sort

However, my medal names go back to being in alphabetic order when pivoted into column names.Sorting the columns of pivot_table (.sort_values(by = 'medals', axis = 1) doesn't help either.Any clues on how to carry this customised order all the way to the pivot_table?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>