2877 Create a DataFrame from List

Problem Statement

Write a solution to create a DataFrame from a 2D list called student_data. This 2D list contains the IDs and ages of some students.

The DataFrame should have two columns, student_id and age, and be in the same order as the original 2D list.

The result format is in the following example.

For the whole problem statement, please refer here.

Plans

  • Use pandas for DataFrame creation.

  • Create a function named createDataframe that accepts a parameter student_data.

  • Use the pd.DataFrame constructor to convert the 2D list into a DataFrame.

  • Specify the column names as student_id and age.

  • Return the created DataFrame from the function.

Solution

import pandas as pd
from typing import List

def createDataframe(student_data: List[List[int]]) -> pd.DataFrame:
    # Convert the 2D list into a DataFrame
    df = pd.DataFrame(student_data, columns=["student_id", "age"])
    
    # Return the DataFrame
    return df

Explanation

  1. Importing Libraries

    • We first import the pandas library, which provides powerful data manipulation capabilities. The List from typing is imported to specify the input type of the function.

  2. Function Definition

    • The function createDataframe is defined to take one argument, student_data, which is expected to be a list of lists (2D list) of integers.

  3. Creating the DataFrame

    • Inside the function, we use pd.DataFrame(student_data, columns=["student_id", "age"]) to create a DataFrame.

    • The first argument is the 2D list student_data, and the columns parameter is used to set the names of the DataFrame columns.

  4. Returning the DataFrame

    • Finally, the created DataFrame df is returned as the output of the function.

Last updated