1

I need to transform the column values to header in python.

    testdf = {'Student_id':['10001','10001','10001','20001','20001','30001','30001','30001'],
          'Subject':['S1','S2','S3','S1','S2','S1','S2','S3'],
          'Mark':['80','60','70','50','70','90','80','40']
         }
testdf = pd.DataFrame(data=testdf)
testdf

enter image description here

I want to have a table like

enter image description here

When I tried below code

testdf.pivot(index="Student_id",columns="Subject")

I am getting like below:

enter image description here

1 Answer 1

3

Add parameter values to DataFrame.pivot and if necessary data cleaning - DataFrame.rename_axis for remove columns name and DataFrame.reset_index for column from index:

df = (testdf.pivot(index="Student_id",columns="Subject", values='Mark')
            .rename_axis(None, axis=1)
            .reset_index())
print (df)
  Student_id  S1  S2   S3
0      10001  80  60   70
1      20001  50  70  NaN
2      30001  90  80   40
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. This is what I am exactly looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.