I have a dataframe like below,
MATERIALNAME CURINGMACHINE HEADERCOUNTER
0 1015 PPU03R 1529
1 3005 PPY12L 305
2 3005 PPY12R 359
3 3005 PPY12R 404
4 K843 PPZB06L 435
5 K928 PPZ03L 1850
I created a pivot table from this df,
pivot = pd.pivot_table(df, index = ['MATERIALNAME', 'CURINGMACHINE'],
values = ['HEADERCOUNTER'],
aggfunc = 'count', fill_value = 0)
pivot
(output)
HEADERCOUNTER
MATERIALNAME CURINGMACHINE
1015 PPU03R 1
3005 PPY12L 1
PPY12R 2
K843 PPZB06L 1
K928 PPZ03L 1
I add subtotals of each material name with the help of this post 'pandas.concat' Pivot table subtotals in Pandas
pivot = pd.concat([
d.append(d.sum().rename((k, 'Total')))
for k, d in pivot.groupby(level=0)
]).append(pivot.sum().rename(('Grand', 'Total')))
My final df is,
HEADERCOUNTER
MATERIALNAME CURINGMACHINE
1015 PPU03R 1
Total 1
3005 PPY12L 1
PPY12R 2
Total 3
K843 PPZB06L 1
Total 1
K928 PPZ03L 1
Total 1
Grand Total 6
I want to sort according to 'HEADERCOUNTER' column. I' m using this code,
sorted_df = pivot.sort_values(by =['HEADERCOUNTER'], ascending = False)
When I sort it, 'MATERIALNAME' column is effecting like below, 'MATERIALNAME' is broken as you can see from 3005 code.
HEADERCOUNTER
MATERIALNAME CURINGMACHINE
Grand Total 6
3005 Total 3
PPY12R 2
1015 PPU03R 1
Total 1
3005 PPY12L 1
K843 PPZB06L 1
Total 1
K928 PPZ03L 1
Total 1
When I sort it, I want to see in that order;
HEADERCOUNTER
MATERIALNAME CURINGMACHINE
Grand Total 6
3005 Total 3
PPY12R 2
PPY12L 1
1015 PPU03R 1
Total 1
K843 PPZB06L 1
Total 1
K928 PPZ03L 1
Total 1
If you have any suggestions to change process, I can try it also.
Edit: I tried BENY's way, but it doesn' t work when data increases.
You can see the not ok result below;