Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫在索引和列上使用多索引重新索引_Python_Python 3.x_Pandas_Dataframe_Pandas Groupby - Fatal编程技术网

Python 熊猫在索引和列上使用多索引重新索引

Python 熊猫在索引和列上使用多索引重新索引,python,python-3.x,pandas,dataframe,pandas-groupby,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

我有一个长数据框,其中包含以下格式的列:

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   
性别、大小、项目组和地区的每个组合都是独特的。因此,不需要执行聚合

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

                    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"])
但立柱问题仍然存在

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

我相信您需要:


是否可以将一些值设置为
x
?Hi@jezrael,很难将它们正确地粘贴格式。它们是数字和字符串的混合体。但考虑到每种组合都是独一无二的,它们并不相关:)所以解决方案对您有效吗?如果没有,请将
x
更改为
a
b
c
1
2
3
,并将其添加到预期输出中。@jezrael抱歉,没有看到您是回答问题的同一个人。是的,解决方案奏效了!谢谢:)
df1 = df.set_index(["item_group","size", "id","gender"]).unstack()