[英]Flattening MultiIndex pivot table in Python pandas
Here's my pivot table column structure (multiindex):这是我的 pivot 表列结构(多索引):
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:如果我做
pivot.columns = pivot.columns.get_level_values(0)
,那么结果是:
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
.我认为解决方案是在
[sales]
和[months]
[]
] 如果仅以一列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”是您的 pivot 表的名称:
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.这将使您的 pivot 表变平,以便您可以执行更强大的可视化或添加其他计算列和转换。 Essentially, you'll go from this:
从本质上讲,你将从这个 go :
To this:对此:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.