how to merge dataframes and create a nested table?

Viewed 28

I've created several objects named 'Student' in python. Each object has attributes containing information like age, name, and gender. Besides, each object has a dataframe, which is a test grade of a student in this year. I want to merge these dataframes and get a nested table without losing their personal information. Here's the python code:

import pandas as pd

class Student:
def __init__(age, name, gender, dataframe):
    self.age = age
    self.name = name
    self.gender = gender
    self.grades = dataframe

    ...

A dataframe looks like this:

enter image description here

I want to get a nested table like this: enter image description here

How can I do this using Pandas? Thanks a lot!

1 Answers

Instead of a nested table as per your screenshot shown, I would recommend that the student ID, name, age, and gender fields to all be filled-up with the same values of the same student instead.

This way, it would allow you to perform additional functions such as groupby aggregation as an example for further use cases.

On your question, the subjects and marks screenshot you shared does not have any identifying key but I would assume that you have something such as the student ID in it. Since you do not wish to lose the student information, you can simply perform a inner join that returns all the rows that matched.

There are a few merging options but pd.merge by default joins with a inner join:

merged = pd.merge(student_df, subjects_df, on = 'student_id')

There are other parameters for pd.merge that you may find in the documentation.

Related