【问题标题】:Pandas Dataframe reshaping , by turning a column into column index, but keeping the rest of the column index intactPandas Dataframe reshaping ,通过将列转换为列索引,但保持列索引的其余部分不变
【发布时间】:2014-05-06 17:37:16
【问题描述】:

我有一个 Pandas 数据框:

           Seq    Part    Type    Grand Total
   ------------------------------------------
    Q001   1      A       total     100
           1      A        ok        80
           1      A        not       20
           2      C       total     150
           2      C        ok       100
           2      C        not       50

我想把它转换成:

           Seq    Part    total    ok      not
   --------------------------------------------
    Q001   1      A       100      80      20
           2      C       150     100      50

意思是我希望 Type 列的值作为列标题,以及它们各自列中总计的关联值,保持 DF 的其余部分不变。

我想为此使用像 transpose/pivot 这样的工具,而不是把整个东西一点一点地复制到另一个 DF 中并按照我的意愿创建它。

感谢您的宝贵时间。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我想我会这样做(使用unstack):

    print df
    
          Q  Seq Part   Type  Grand_Total
    0  Q001    1    A  total          100
    1  Q001    1    A     ok           80
    2  Q001    1    A    not           20
    3  Q001    2    C  total          150
    4  Q001    2    C     ok          100
    5  Q001    2    C    not           50
    

    为方便起见,我将您的第一列称为Q(如果它是您设置中的索引,请重置索引):

    df = df.set_index(['Q','Seq','Part','Type']).unstack(['Type'])
    print df
    
                  Grand_Total          
    Type                 total   ok  not
    Q    Seq Part                       
    Q001 1   A             100   80   20
         2   C             150  100   50
    

    我认为这可以满足您的需求,但如果您不喜欢分层列索引,请执行以下操作:

    df.columns = df.columns.get_level_values(1)
    print df.reset_index()  
    
    Type     Q  Seq Part  total   ok  not
    0     Q001    1    A    100   80   20 
    1     Q001    2    C    150  100   50
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 2019-05-04
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多