How can I convert columns to rows in Pandas?

前端 未结 3 1634
Happy的楠姐
Happy的楠姐 2021-01-23 16:48

I have something like this:

Values     Time
  22        0
  45        1
  65        2
  78        0
  12        1
  45        2

and I want this

3条回答
  •  执笔经年
    2021-01-23 17:00

    This is pivot creating the index with cumcount

    df['idx'] = 'Val' + (df.groupby('Time').cumcount()+1).astype(str)
    df.pivot(index='idx', columns='Time', values='Values').rename_axis(None)
    

    Output:

    Time   0   1   2
    Val1  22  45  65
    Val2  78  12  45
    

提交回复
热议问题