-1

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
helpme
  • 163
  • 3
  • 9
  • Why do you need 7 columns named '1997'? Only 1 is not enough? – Mário César Fracalossi Bais May 17 '22 at 22:18
  • [Please don't post pictures of text](https://meta.stackoverflow.com/q/285551/4518341). Instead, copy the text itself, [edit] it into your post, and use the formatting tools like [code formatting](/editing-help#code). See [How to make good reproducible pandas examples](/q/20109391/4518341) for specifics. – wjandrea May 17 '22 at 22:19
  • shoot you are right. My bad will edit it. – helpme May 17 '22 at 22:19
  • 2
    Does this answer your question? [How can I pivot a dataframe?](https://stackoverflow.com/questions/47152691/how-can-i-pivot-a-dataframe) – Rodalm May 17 '22 at 22:34

1 Answers1

1

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

wjandrea
  • 28,235
  • 9
  • 60
  • 81