Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening MultiIndex pivot table in Python pandas

Here's my pivot table column structure (multiindex):

      col2  col3  col4  sales

month                   month_1  month_2  month_3

I would like to flatten it to:

      col2  col3  col4  month_1  month_2  month_3

If I do pivot.columns = pivot.columns.get_level_values(0), then the result is:

      col2  col3  col4  sales  sales  sales

What do I do?

like image 340
currentlyunknown Avatar asked Oct 24 '25 19:10

currentlyunknown


1 Answers

I think solution is remove [] around [sales] and [months] if pivoting only by one column sales.

So code is:

 pivot = (pd.pivot_table(df, 
                         index=['col2','col3','col4'],
                         columns='month', 
                         values='sales')
            .reset_index()
            .rename_axis(None, axis=1))
like image 160
jezrael Avatar answered Oct 26 '25 07:10

jezrael