1

I have a pandas DataFrame as following, showing the scores of students in multiple subjects:

       Name    Subject    Score
0       Tom          A       91
1       Tom          B       92
2       Tom          C       93
3       Bob          A       94
4       Bob          C       95
5       Ali          B       96
6       Ali          C       97

Note that not every student has scores in all subjects. I want to pivot it into a DataFrame like this:

      Name     A     B     C
0      Tom    91    92    93
1      Bob    94          95    
2      Ali          96    97

The goals to achieve in this pivot:

  1. group the scores by 'Name'
  2. insert columns of subjects
  3. arrange the scores at the crossing space of Name and subjects

I'm new to pandas but I looked into DataFrame.pivot_table(), while unfortunately couldn't figure out the right way.

2 Answers 2

3

You were right on with using a pivot_table to solve this:

df = df.pivot_table(index='Name', values='Score', columns='Subject') \
    .reset_index() \
    .rename_axis(None, axis=1)
print(df)

Output:

  Name     A     B     C
0  Ali   NaN  96.0  97.0
1  Bob  94.0   NaN  95.0
2  Tom  91.0  92.0  93.0

Pivot also works in this case:

df = df.pivot(index='Name', values='Score', columns='Subject') \
    .reset_index() \
    .rename_axis(None, axis=1)
Sign up to request clarification or add additional context in comments.

Comments

2

Here is the solution

import pandas as pd
df= DATAFRAME [ as yours]
df1=df.pivot(index='Name',columns = 'Subject', values = 'Score').fillna('').round(decimals=0).astype(object)

Output enter image description here

Comments

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.