I have created a pivot table with a three-level multi-index (Group, Product, and State). The state level is automatically sorted alphabetically, but I need to change the ordering to a custom, non-alphabetical ordering. I may need to also re-order the Group and Product levels in similar fashion.
pivot = data.pivot_table(rows=['Group', 'Product', 'State'],
values = ['JAN', 'FEB', 'MAR', 'APR', 'MAY',
'JUN', 'JUL', 'AUG', 'SEP', 'OCT',
'NOV', 'DEC'], fill_value=0, margins=True aggfunc=sum)
cols = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
#I used this method to prevent the month names from being alphabetically sorted
pivot = pivot[cols]
A portion of the pivot table looks like this...
JUN JUL AUG
Group Product State
Group A Product A AZ 0 0 0
CO 0 0 0
GA 0 0 0
IL 0 0 0
IN 0 0 0
KS 0 0 0
MN 0 0 0
MO 0 0 0
I need the ordering of the states to be as follows...
state_order = ['AZ','CO','ID','NV','OR','UT','WA','IA','KS','MN','MO','NE','ND','SD','GA','IL','IN','OH','WI']
I tried the reindex_axis() fuction, feeding in my list above and specifying level=2. However, the states were still sorted in alphabetical order.
Any insights into a fix would be much appreciated.