Home > Back-end >  How to group and transpose my dataframe in a specific way?
How to group and transpose my dataframe in a specific way?

Time:11-12

I have a dataframe:

id    type   value
a      K1     10
b      K1     14
c      K1     8
a      M4     17
b      M4     20
d      M4     34
e      M4     90

I want to group by id and then transpose in such way to get this:

id    K1   M4
a     10   17
b     14   20
c     8    NA
d     NA   34
e     NA   90

How to do that? Which functions may I use?

CodePudding user response:

Pivot table does exactly what you want.

df.pivot(index='id', columns='type', values='value')
  • Related