0

I have a sample dataset below:

ID Name Test Point
1 Tom Math 5
1 Tom Bio 7
2 Jerry Math 10
2 Jerry Bio 8
2 Jerry Data 9

I want to transform grouped dataframe to result below:

ID Name Bio Data
1 Tom 7 NaN
2 Jerry NaN 9

Below is my code:

# importing pandas as pd
import pandas as pd
import numpy as np

# creating a dataframe
df = pd.DataFrame({
                   'Id': [1,1,2,2,2],
                   'Name': ['Tom', 'Tom', 'Jerry', 'Jerry','Jerry'],
                   'Test': ['Math', 'Bio', 'Math', 'Bio','Data'],
                   'Value': [5, 7, 10, 8, 9]})

df

Grouped

grouped = df.groupby(['Id','Name']).last()
grouped.head()

When I pivot a groupeddataframe raise error. How can I solve this problem?

pivoted = grouped.pivot(index='Name', columns='Test', values='Value')\
            .reset_index()
pivoted.columns.name=None
print(pivoted)

Thanks in advance.

nvtthang
  • 604
  • 1
  • 10
  • 26
  • 1
    Use `df.pivot_table(index=['Id','Name'], columns='Test', values='Value', aggfunc='last').reset_index()` – jezrael May 23 '22 at 09:58

0 Answers0