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

Number: 3062

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Meta, Microsoft, Bloomberg, Apple, Adobe


Problem Description

Given a 2D list called student_data that contains student IDs and ages, create a DataFrame with two columns named student_id and age. The DataFrame should maintain the same order as given in the list.


Key Insights

  • The task involves simple data structure conversion from a list to a DataFrame.
  • In Python, the pandas library provides a straightforward way to create and label DataFrames.
  • For languages that do not have a direct DataFrame implementation, you can simulate the structure with an array or list of objects/structs.
  • The problem emphasizes maintaining the order from the original list.

Space and Time Complexity

Time Complexity: O(n), where n is the number of rows in student_data. Space Complexity: O(n), for storing the converted data structure.


Solution

We will convert the given 2D list into a DataFrame. In Python, the pandas library offers a concise way to achieve this by specifying the column names during DataFrame creation. For other languages, we simulate a DataFrame by creating appropriate data structures (e.g., list of objects or structs) that contain the student_id and age fields. The solution iterates through each row in the list and assigns the values to the corresponding fields in the data structure, ensuring that the original order is preserved.


Code Solutions

# Import the pandas library for DataFrame creation
import pandas as pd  

# Given 2D list containing student ID and age data
student_data = [
    [1, 15],
    [2, 11],
    [3, 11],
    [4, 20]
]

# Create a DataFrame using the list and specify the column names
df = pd.DataFrame(student_data, columns=['student_id', 'age'])

# Print the DataFrame to verify its structure
print(df)
← Back to All Questions