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 parameterstudent_data
.Use the
pd.DataFrame
constructor to convert the 2D list into a DataFrame.Specify the column names as
student_id
andage
.Return the created DataFrame from the function.
Solution
Explanation
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.
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.
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.
Returning the DataFrame
Finally, the created DataFrame df is returned as the output of the function.
Last updated