Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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 Groupby作为具有多索引的列_Python_Pandas_Pandas Groupby_Multi Index - Fatal编程技术网

Python Groupby作为具有多索引的列

Python Groupby作为具有多索引的列,python,pandas,pandas-groupby,multi-index,Python,Pandas,Pandas Groupby,Multi Index,我有一个类似于 df=pd.DataFrame( pd.np.random.randint(1,10,(20,2)),, 索引=[“a”、“b”、“c”、“d”]*5, 列=[“foo”,“bar”], ) 看起来像这样 我试图将其转换为以下多索引形式:4个轴标签中的每一个都有两列,每个轴标签都有一个“foo”和“bar”子列: 我尝试过摆弄df.groupby(df.index),但我不知道如何将组转换为列。在索引中使用多索引,然后通过以下方式重塑并更改列中多索引的顺序: df1 = (

我有一个类似于

df=pd.DataFrame(
pd.np.random.randint(1,10,(20,2)),,
索引=[“a”、“b”、“c”、“d”]*5,
列=[“foo”,“bar”],
)
看起来像这样

我试图将其转换为以下多索引形式:4个轴标签中的每一个都有两列,每个轴标签都有一个“foo”和“bar”子列:

我尝试过摆弄
df.groupby(df.index)
,但我不知道如何将组转换为列。

在索引中使用
多索引,然后通过以下方式重塑并更改列中
多索引的顺序:

df1 = (df.set_index(df.groupby(level=0).cumcount(), append=True)
         .unstack(0)
         .swaplevel(0,1, axis=1)
         .sort_index(axis=1, level=[0,1], ascending=[True, False]))
print (df1)
    a       b       c       d    
  foo bar foo bar foo bar foo bar
0   6   8   1   6   8   4   6   1
1   2   6   4   5   3   1   5   4
2   2   5   2   9   5   4   8   9
3   5   2   6   6   7   3   2   9
4   4   8   9   6   4   2   1   5