代码之家  ›  专栏  ›  技术社区  ›  fume_hood_geologist

通过在Pandas中分组将分组的堆叠柱转换为多列

  •  0
  • fume_hood_geologist  · 技术社区  · 8 年前

    我使用groupby函数将数据帧组织成这样:

    Compound   Sample    Concentration  x   y
    Benzene    A         15             Ax  Ay 
               B         20             Bx  By
               C         17             Cx  Cy
    
    Toluene    A         23             Ax  Ay
               B         40             Bx  By
    
    Xylene     A         70             Ax  Ay
               B         62             Bx  By
               C         55             Cx  Cy
               D         32             Dx  Dy
    

    如何将列拆分为多个高度相同的列,并将其分组为列名?我想实现这样的目标:

    Sample    Benzene   Toluene    Xylene    x   y
    A         15        23         70        Ax  Ay 
    B         20        40         62        Bx  By
    C         17        0          55        Cx  Cy
    D         0         0          32        Dx  Dy    
    

    编辑 在使用groupby函数后,我丢失了索引,我的数据过去是这样的:

        Compound       Sample        Concentration          x   y
    1    Benzene       A             15                     Ax  Ay 
    5    Benzene       B             20                     Bx  By
    6    Benzene       C             17                     Cx  Cy
    0    Toluene       A             23                     Ax  Ay
    4    Toluene       B             40                     Bx  By
    2    Xylene        A             70                     Ax  Ay
    3    Xylene        B             62                     Bx  By
    7    Xylene        C             55                     Cx  Cy
    8    Xylene        D             32                     Dx  Dy
    

    我按化合物排序,以便重新排列所有索引,这些索引最初是按样本排序的

    1 回复  |  直到 8 年前
        1
  •  0
  •   Jacob H    8 年前

    根据你的帖子,还不清楚你的哪些列在索引中。如果没有(可以使用df.reset\u index()强制),则可以执行以下操作:

    df.set_index(['Compound', 'Sample', 'x', 'y'], inplace = True)
    df = df['Concentration']
    df = df.unstack(level = 0)
    df.reset_index(inplace = True)
    

    这与输出不匹配的唯一方式是,现在x和y列位于数据的左侧。由于这些列看起来很容易从示例字母中构建,因此在转换后添加它们可能更容易。也就是说,如果您的分组by给您提供了一个数据框架,索引中包含化合物和样本,并且浓度是唯一的列,那么您只需执行以下操作:

    df = df['Concentration'].unstack(level = 0)
    

    然后添加x和y列。

    编辑:从您的原始数据中,您也可以这样做,这与您使用groupby所做的一样,并在一个步骤中重塑形状:

    df2 = pd.pivot_table(df, index = ['Sample', 'x', 'y'], columns = 'Compound', values = 'Concentration')