Change pandas Multi-index from Row to Column

Currently have a dataframe generated by groupby() in the following shape:

                 #         avg      total  unique
year month                                       
2014 1       241.0   64.668050   15585.00   237.0
     2       358.0   65.197877   23340.84   347.0
     3       347.0   60.336715   20936.84   340.0
     4       179.0   61.071788   10931.85   172.0
2015 1        57.0   54.562982    3110.09    56.0
     2       140.0   76.007143   10641.00   138.0
     3        85.0   79.929412    6794.00    80.0
     4        89.0   70.000000    6230.00    87.0

I would like to pivot it to the following shape:

        2014                                  2015
        #       avg         total      unique     #         avg      total  unique
month 
1       241.0   64.668050   15585.00   237.0   57.0   54.562982    3110.09    56.0
2       358.0   65.197877   23340.84   347.0  140.0   76.007143   10641.00   138.0
3       347.0   60.336715   20936.84   340.0   85.0   79.929412    6794.00    80.0
4       179.0   61.071788   10931.85   172.0   89.0   70.000000    6230.00    87.0

I've tried various permutations of pivot, pivot_table, unstack, reorder_levels, etc, but none get me to the correct format.

I suspect there's a very simple answer I'm missing :)

1 answer

  • answered 2018-03-20 22:22 piRSquared

    df.unstack(0).swaplevel(0, 1, 1).sort_index(1)