取消堆叠并重新排序 pandas 数据帧

Unstack and reorder pandas dataframe

我四处搜索,但找不到如何取消堆叠和重新排序 pandas 数据帧的解决方案。

假设我有以下数据框:

df = pd.DataFrame({'type': [1, 2, 2, 1, 2, 1, 2, 1, 2, 2],
                   'band': ['A', 'B', 'C', 'C', 'B', 'B', 'A', 'A', 'B', 'C'],
                   'val': [0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27]})

我可以按 'type''band' 分组以获得两个维度的平均值,并使用 unstack()'band' 显示为列:

df.groupby(['type', 'band']).mean().unstack(level=1)

我的问题是,如何对列重新排序,使它们按降序(或更一般地,任意排序)顺序排列?

输出如下所示:

    val
band    A   B           C
type            
1   0.215   0.230000    0.210
2   0.240   0.223333    0.235

我想要的是:

    val
band    C   B           A
type            
1   0.210   0.230000    0.215
2   0.235   0.223333    0.240

实际上,我有超过 3 列。

您似乎想要 sort_index 列:

df.groupby(['type', 'band']).mean().unstack(level=1)\
    .sort_index(axis=1, ascending=False)

结果:

        val              
band      C      B      A
type                     
1     0.210  0.230  0.215
2     0.235  0.223  0.240

至于任意订单:假设您的订单是 "C, A, B"。通常,您必须直接指定它。

order = list('CAB')
df[order]

df.groupby(['type', 'band']).mean().unstack(level=1)的输出是另一个DataFrame。您可以执行以下操作:

df = df.groupby(['type', 'band']).mean().unstack(level=1)
df = df.reindex_axis(sorted(df.columns, reverse=True), axis=1)