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

用堆栈和非堆栈对熊猫数据帧进行整形

  •  3
  • user96564  · 技术社区  · 8 年前

    我正试图弄乱熊猫的叠放。我想知道是否有可能用这种方式改变我的数据。

    这是我正在练习的示例数据。

    ID,Value1,Value2
    1,3,12
    1,4,13
    1,5,14
    1,6,15
    1,7,16
    2,8,17
    2,9,18
    2,10,19
    2,11,20
    

    我想用这种方式重塑。

    ID 
    1   Index(Extra Column) Value1, value2
        1                      3    12
        2                      4    13
        3                      5    14
        4                      6    15
        5                      7    16
    
    2
        1                      8    17
        2                      9    18
        3                      10   19
        4                      11   20
    

    我试过这个

    df1 = pd.DataFrame(df[['Value1', 'Value2']], index= df['ID']).stack()
    

    df1 = df.set_index(['ID']).stack()
    

    这会将值1和值2从列更改为不需要的行。

    有什么想法吗?

    3 回复  |  直到 8 年前
        1
  •  4
  •   cs95 abhishek58g    8 年前

    set_index cumcount

    df.set_index(['ID', df.groupby('ID').cumcount() + 1])
    
          Value1  Value2
    ID                  
    1  1       3      12
       2       4      13
       3       5      14
       4       6      15
       5       7      16
    2  1       8      17
       2       9      18
       3      10      19
       4      11      20
    

    concat

    pd.concat({k : g.reset_index(drop=True) for k, g in df.drop('ID', 1).groupby(df.ID)})
    
         Value1  Value2
    1 0       3      12
      1       4      13
      2       5      14
      3       6      15
      4       7      16
    2 0       8      17
      1       9      18
      2      10      19
      3      11      20
    
        2
  •  3
  •   BENY    8 年前

    df.groupby('ID')[['Value1','Value2']].apply(lambda x : x.reset_index(drop=True))
    Out[662]: 
          Value1  Value2
    ID                  
    1  0       3      12
       1       4      13
       2       5      14
       3       6      15
       4       7      16
    2  0       8      17
       1       9      18
       2      10      19
       3      11      20
    
        3
  •  2
  •   piRSquared    8 年前

    defaultdict count

    from itertools import count
    from collections import defaultdict
    
    d = defaultdict(count)
    
    df.set_index(['ID', np.array([next(d[x]) for x in df.ID])])
    
          Value1  Value2
    ID                  
    1  0       3      12
       1       4      13
       2       5      14
       3       6      15
       4       7      16
    2  0       8      17
       1       9      18
       2      10      19
       3      11      20