Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to group by column values into index?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading