Python: sorting index column in pivot table by custom order

Viewed 240

as result of dataframe manipulation

week_days = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}
week_view['day_week_name'] = week_view ['day_week'].apply(lambda x: week_days[x]) 
...
week_view.pivot_table(index = ['paymentType','type'], columns=['day_week_name'], aggfunc={'value':'sum'}, fill_value=0).sort_index(axis = 1, ascending = False)

I have result:

enter image description here

is there way to get it sorted in normal way where 'monday' is the first and 'sunday' is the last column?

i tried to use "key=" argument for .sort_index(), but got error back:

TypeError: sort_index() got an unexpected keyword argument 'key'

UPDATE (a kind of solution) with help of your comments, i find a way to solve the task. you have to use pd.Categorical to get it sorted. But the problem with pivot table, that zero-rows will be add to final table (that is non if you are not using categorization). You have to add some more lines to get the result as desired:

week_view['day_week_name']  = pd.Categorical(week_view['day_week_name'], ['Понедельник','Вторник','Среда','Четверг','Пятница','Суббота','Воскресенье'])

week_pivot = week_view.pivot_table(index = ['paymentType','type'], columns=['day_week_name'], aggfunc={'value':'sum'}, fill_value=0).sort_index(axis = 1)
week_series = (week_pivot != 0).any(axis=1)
week_pivot.loc[week_series]

enter image description here

0 Answers
Related