Pandas 在多级索引中旋转一级索引

Pandas 在多级索引中旋转一级索引,pandas,Pandas,假设我有一个具有多索引的数据帧: col1 col2 date id 2016-04-05 A 100 99 2016-04-05 B 101 98 2016-04-05 C 102 95 ... 2016-04-12 A 90 65 2016-04-12 B 91 62 2016-04-12 C 9

假设我有一个具有多索引的数据帧:

                   col1   col2
 date        id    
 2016-04-05   A     100     99
 2016-04-05   B     101     98
 2016-04-05   C     102     95
 ...
 2016-04-12   A      90     65
 2016-04-12   B      91     62
 2016-04-12   C      93     64
如何使用col1并将索引的“id”级别透视到一个框架中,其中索引仅为“date”,列为“id”的值

       date     A     B     C 
 2016-04-05   100   101   102
 2016-04-06    80    87    83
 ...
 2016-04-12    90    91    93
谢谢

我想你可以先
col2
,然后是,最后是:

下一个解决方案包括:


在取消堆叠之前从df中删除col2,那么您的答案就是:-)
df = df.drop('col2', axis=1).unstack('id')
df.columns = df.columns.droplevel(0)
df = df.rename_axis(None, axis=1).reset_index()
print df
        date    A    B    C
0 2016-04-05  100  101  102
1 2016-04-12   90   91   93
print df.reset_index()
        .pivot(index='date', columns='id', values='col1')
        .rename_axis(None, axis=1)
        .reset_index()

        date    A    B    C
0 2016-04-05  100  101  102
1 2016-04-12   90   91   93