Search code examples
pythonpandaspivot-table

Reordering pivot table headers


I have the output to a pivot table which looks as follows

enter image description here

I would like the output to be reordered as shown below

enter image description here

Having looked at other similar posts, it's some kind of post processing on the pivot table. I have tried pd.swap_levels(0, 1, axis=1) but it does not give the correct results. Note I also want to reverse the order of the weeks so that it becomes 4 to 1.

Can anyone help with the required syntax to get the desired outcome?


Solution

  • First, swaplevel then sort_index in descending order but use sort_remaining=False to maintain the other level order:

    # Output
    >>> df.swaplevel(axis=1).sort_index(axis=1, level=0, ascending=False, sort_remaining=False)
    
    Weeknum    4            3            2            1        
            Late Neg Pos Late Neg Pos Late Neg Pos Late Neg Pos
    0          D   H   L    C   G   K    B   F   J    A   E   I
    
    # Input
    >>> df
            Late          Neg          Pos         
    Weeknum    1  2  3  4   1  2  3  4   1  2  3  4
    0          A  B  C  D   E  F  G  H   I  J  K  L