Skip to content
Advertisement

pandas sorting by subtotal

I have a multi indexed dataframe like below. I’ m giving the full data consciously, because when I try this solution pandas multi index sort with several conditions with small data it is OK, but when I try with full data, it doesn’t work.

Multi-indexes are: ‘MATERIALNAME’ and ‘CURINGMACHINE’

‘MATERIALNAME’: level 0

‘CURINGMACHINE’: level 1

JavaScript

I want to sort this df according to sub-totals of each level 0 ‘MATERIALNAME’ column.

Edit: This shouldn’ t happen.

enter image description here

Advertisement

Answer

First, I’d reset the index so that you have again a data frame (now it looks like a pandas series with multi-index)

JavaScript

Then you can add new column with the values you want to sort by

JavaScript

Finally, just sort it (highest first). If the subtotal is same in multiple groups, it will sort them by group identifier.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement