Maday Hernandez
Maday Hernandez

Reputation: 31

Reshape dataframe with pandas turning column name into values

I want to turn this:


    dfe=pd.DataFrame({"ID":['001','001','001','002','002','002'], "Course":['Math','Spn','Eng','Math','Spn','Eng'], "1st":[100,100,90,100,100,88],"2nd":[99,100,90,100,99,99],
     "3rd":[80,100,90,100,99,100] })

into:


dfi=pd.DataFrame({"ID":['001','001','001','002','002','002'], "Math":[100,99,80,100,100,100], "Spn":[100,100,100,100,99,99], "Eng":[90,90,90,88,99,100], "Semester":['1st','2nd','3rd','1st','2nd','3rd'] })

I tried with pivot_table but I don't know how to create the "Semester" column.

Upvotes: 1

Views: 155

Answers (1)

anky
anky

Reputation: 75100

you can try the same pivot_table with a little adjustment:

(dfe.pivot_table(index="ID",columns="Course").stack(0)
  .rename_axis(['ID',"Sem"]).reset_index().rename_axis(None,axis=1))

         ID  Sem  Eng  Math  Spn
0       001  1st   90   100  100
1       001  2nd   90    99  100
2       001  3rd   90    80  100
3       002  1st   88   100  100
4       002  2nd   99   100   99
5       002  3rd  100   100   99

Upvotes: 1

Related Questions