Home > Software engineering >  Transpose on Pandas Python
Transpose on Pandas Python

Time:10-13

i have data frame like this:

ID   A     B    C
1    2001  10   5 
1    2002  15   6

I want to do transpose so the result look like:

ID   B_2001    C_2001   B_2002     C_2002
1     10          5       15         6

Is there any way to do it with pandas?

CodePudding user response:

You are looking for pivot:

# pivot gives you correct data structure
out = df.pivot(index='ID', columns='A')

# rename the columns
out.columns = ['_'.join(map(str, x)) for x in out.columns]

Output:

    B_2001  B_2002  C_2001  C_2002
ID                                
1       10      15       5       6
  • Related