【问题标题】:Swap level-one from index with column level (Pandas Multiindex Dataframe)将一级索引与列级交换(Pandas Multiindex Dataframe)
【发布时间】:2016-02-16 21:14:41
【问题描述】:

我有一个多索引的 pandas.Dataframe,它是这样的:

          BAZ    PAL
Foo  Bar          
124   1    A     B
      2    C     D
134   1    E     F
      2    G     H

我需要以适当的方式将一级索引与列交换。我需要得到这样的结果:

         124 134
Coo Bar
BAZ 1    A   E
    2    C   G
PAL 1    B   F
    2    D   H

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要取消堆叠现有的索引级别Foo,堆叠您想要的列“Coo”,然后重新排列索引级别。交换索引级别后,您可能想要对其进行排序。最后,您可能希望删除所有值的列名 (val)。

    df = (pd.DataFrame({'Foo': [124, 124, 134, 134] * 2, 
                        'Bar': [1, 2, 1, 2] * 2, 
                        'Coo': ['BAZ'] * 4 + ['PAL'] * 4, 
                        'val': list('ACEGBDFH')})
          .set_index(['Foo', 'Bar', 'Coo'])
          .unstack('Coo'))
    
    >>> df
            val    
    Coo     BAZ PAL
    Foo Bar        
    124 1     A   B
        2     C   D
    134 1     E   F
        2     G   H
    
    df = df.unstack('Foo').stack('Coo')
    df.index = df.index.swaplevel(0, 1)
    
    >>> df
            val    
    Foo     124 134
    Coo Bar        
    BAZ 1     A   E
    PAL 1     B   F
    BAZ 2     C   G
    PAL 2     D   H
    
    df.sort_index(inplace=True)
    
    >>> df
            val    
    Foo     124 134
    Coo Bar        
    BAZ 1     A   E
        2     C   G
    PAL 1     B   F
        2     D   H
    
    df.columns = df.columns.droplevel()
    
    >>> df
    Foo     124 134
    Coo Bar        
    BAZ 1     A   E
        2     C   G
    PAL 1     B   F
        2     D   H
    

    【讨论】:

      猜你喜欢
      • 2015-07-19
      • 2019-01-26
      • 2020-05-19
      • 2021-03-27
      • 1970-01-01
      • 2017-10-16
      • 2018-06-24
      • 2022-06-11
      相关资源
      最近更新 更多