使用索引和列上的Multiindex重新编制熊猫索引

时间:2018-10-24 12:34:18

标签: python python-3.x pandas dataframe pandas-groupby

我有一个长数据框,这些列的格式如下:

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   

性别,大小,item_group和地区的每种组合都是唯一的。因此,无需执行聚合。

我想将索引和列重新索引到这种类型的输出,并且单元格值保持不变

                    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                       

也就是说,具有索引以及具有多索引的列。我能够通过调用以下内容来执行索引部分:

df.groupby(["item_group","size"])

但是列问题仍然存在。

如何从现有数据框中创建列多索引?

1 个答案:

答案 0 :(得分:1)

我相信您需要set_indexunstack

df1 = df.set_index(["item_group","size", "id","gender"]).unstack()
相关问题