Pandas 在索引和列上使用多索引重新索引 [英] Pandas re-indexing with Multiindex on Index AND Columns
本文介绍了Pandas 在索引和列上使用多索引重新索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长的数据框,其中包含以下格式的列:
I have a long dataframe with these columns in this format:
id gender size region_a_count region_b_count item_group
x m x x x x
x f x x x x
x f x x x x
x m x x x x
x f x x x x
x m x x x x
性别、大小、商品组和地区的每个组合都是独一无二的.所以不需要进行聚合.
Each combination of gender, size,item_group and region is unique. So there is no need to perform an aggregation.
我想将索引和列重新索引到这种类型的输出,而单元格值保持不变
I want to reindex the index and columns to this type of output, with the cell values staying the same
region_a region_b region_c
m f m f m f
(index of size)
item_group 1
2
3
item_group 1
2
3
也就是说,具有索引以及具有多索引的列.我能够通过调用来执行索引的部分:
That is, with index as well as columns having a multiindex. I was able to perform the part for the index by calling:
df.groupby(["item_group","size"])
但是列问题仍然存在.
如何从现有数据帧创建多索引列?
How can I create the column multiindex from the existing dataframe?
推荐答案
I believe you need set_index
with unstack
:
df1 = df.set_index(["item_group","size", "id","gender"]).unstack()
这篇关于Pandas 在索引和列上使用多索引重新索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文