简体   繁体   中英

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?

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:

数据透视表

To this:

平面枢轴表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM