Search code examples
pythonpandasmulti-index

Switch pandas Multi-index level column to header row


I have this dataframe (result of a groupbyagg) :

![enter image description here

Unitcount is the only column. Product and Day are multi-indexes. I'd like to know if there is any way to move the 'day' multi-index level to headers. Here's the output I am looking for :

enter image description here

The order of days is not important for now, i'm just curious to know if this kind of switch is possible with Pandas. Thanks!


Solution

  • Use Series.unstack with DataFrame.reindex for correct order of columns:

    cols = ['LUNES', 'MARTES', 'MIÉRCOLES', 'JUEVES', 'VIERNES', 'SÁBADO', 'DOMINGO']
    df = df['day'].unstack(fill_value=0).reindex(cols, axis=1)