我有一个类似于的数据框
df = pd.DataFrame(
pd.np.random.randint(1, 10, (20, 2)),
index=["a", "b", "c", "d"] * 5,
columns=["foo", "bar"],
)
看起来像这样
我试图将其转换为以下多索引形式:4 个轴标签中的每一个都有两列,每个标签都有一个“foo”和“bar”子列:
我尝试摆弄df.groupby(df.index)
,但后来我不知道如何将组变成列。
最佳答案
使用GroupBy.cumcount
对于索引 DataFrame.set_index
中的 MultiIndex
,然后通过 DataFrame.unstack
reshape 形状并将列中 Multiindex
的顺序更改为 DataFrame.swaplevel
与 DataFrame.sort_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
关于python - Groupby 作为具有 MultiIndex 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57338402/