We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Create a DataFrame from List

Difficulty: Easy


Problem Description

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.

Key Insights

  • The input is a 2D list where each inner list represents a student's ID and age.
  • The output should be a structured DataFrame with predefined column names.
  • The order of the entries in the DataFrame must match the input list.

Space and Time Complexity

Time Complexity: O(n), where n is the number of students since we need to iterate through the entire list to create the DataFrame.
Space Complexity: O(n), for storing the DataFrame's data.

Solution

To solve this problem, we will utilize a DataFrame data structure to organize the student data. We will iterate through each inner list in the student_data, extracting the student ID and age, and then populate the DataFrame with this information. The final DataFrame will have two columns named student_id and age.

Code Solutions

import pandas as pd

def create_dataframe(student_data):
    # Create a DataFrame using the provided 2D list
    df = pd.DataFrame(student_data, columns=['student_id', 'age'])
    return df

# Example usage:
student_data = [
    [1, 15],
    [2, 11],
    [3, 11],
    [4, 20]
]
df = create_dataframe(student_data)
print(df)
← Back to All Questions