Home > Software engineering >  How to group by column values into index?
How to group by column values into index?

Time:05-18

I have dataframe that looks like this

Date    group   value
1997    a       num
1997    b       num
1997    c       num
1997    d       num
1997    e       num
1997    f       num
1997    g       num
1998    a       num
1998    b       num
1998    c       num
1998    d       num
1998    e       num
1998    f       num
1998    g       num
1999    a       num

How do I make it look like this

index   group   1997    1998    1999    2000    2001    2002
0       a       num     num     num     num     num     num
1       b       num     num     num     num     num     num
2       c       num     num     num     num     num     num
3       d       num     num     num     num     num     num
4       e       num     num     num     num     num     num
5       f       num     num     num     num     num     num
6       g       num     num     num     num     num     num

CodePudding user response:

Make a pivot table.

>>> df.pivot_table(columns='Date', values='value', index='group', aggfunc='first')
Date  1997 1998 1999
group               
a      num  num  num
b      num  num  NaN
c      num  num  NaN
d      num  num  NaN
e      num  num  NaN
f      num  num  NaN
g      num  num  NaN

(Here data is missing since I'm only using the input data you provided.)

  • Related