Flattening MultiIndex pivot table in Python pandas

Viewed 2643

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?

2 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))

I would do something like this, where "pivot" is the name of your pivot table:

pivot_flat = pd.DataFrame(pivot.to_records())

This will flatten your pivot table so you can perform more robust visualizations or add in other calculated columns and transformations. Essentially, you'll go from this:

pivot table

To this:

flat pivot table

Related