Cuteufo
Cuteufo

Reputation: 575

Python pandas: pivot DataFrame columns in rows

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.

Upvotes: 1

Views: 5797

Answers (2)

Vivs
Vivs

Reputation: 475

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

Upvotes: 2

Henry Ecker
Henry Ecker

Reputation: 35636

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)

Upvotes: 3

Related Questions