Reordering columns/rows of a pivot_table?

pandas, pivot-table, python

Solution

Using Categories, introduced in pandas 0.15, the 'day' and 'smoker' columns can be converted to categories with predefined order. The pivot_table() would keep them sorted.

>>> pt = pd.pivot_table(df, 'tip_pct', index=['sex', 'day'], columns='smoker', aggfunc=pd.np.sum)

smoker      No  Yes
sex    day         
Female Fri   0    4
       Sat   0    5
       Sun   0    5
       Thu   9    3
Male   Fri   0    4
       Sat   1    5
       Sun   1    5
       Thu   9    3

>>> df["day"] = df["day"].astype('category', categories=["Thu", "Fri", "Sat", "Sun"])
>>> df["smoker"] = df["smoker"].astype('category', categories = ["Yes", "No"])
>>> pt = pd.pivot_table(df, 'tip_pct', index=['sex', 'day'], columns='smoker', aggfunc=pd.np.sum)

smoker      Yes  No
sex    day         
Female Thu    3   9
       Fri    4   0
       Sat    5   0
       Sun    5   0
Male   Thu    3   9
       Fri    4   0
       Sat    5   1
       Sun    5   1

Problem

pandas's pivot_table seems to return columns only in alphabetical order, such that `pivot_table(tips, 'tip_pct', rows=['sex', 'day'], cols='smoker', aggfunc=len)` gives: ``` smoker No Yes sex day Female Fri 2 7 Sat 13 15 Sun 14 4 Thur 25 7 Male Fri 2 8 Sat 32 27 Sun 43 15 Thur 20 10 ``` If I wanted to put `Thur` above `Fri`, and `Yes` to the left of `No`, how would I go about it?

Original source

Related problems