Talentd
FleetCode
Make and follow sheets.Sign in

Create a DataFrame from List solution and explanation

Easy4 min read81.3% acceptanceUpdated 9 Apr 2026
2877. Create a DataFrame from List | LeetCode | Python | PandasYou Data And AI · 1:47 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. 2877. Create a DataFrame from List | LeetCode | Python | PandasYou Data And AI · 1:47 · 2K views
  2. Create a DataFrame from List | Pandas Data Structures | #pandas #python #leetcodeLearn With Chirag · 13:39 · 706 views
  3. Create a DataFrame from List. LeetCode 2877CuteLeetCrafter · 1:52 · 432 views
  4. #LeetCode 2877 | Create a DataFrame from List #PythonSleepy Cracker · 1:04 · 220 views
  5. LeetCode - 2877 Solution || Create DataFrames || Python || #coding #python #2877 #trend #educationCODING WORLD · 8:24 · 197 views
  6. LeetCode 2877: Convert 2D List to DataFrame in PandasScott Hacks Code · 2:53 · 171 views
  7. 1. Create a DataFrame from List LeetCodeJohn Sharon Kumar J · 3:36 · 165 views
  8. LeetCode 2877 Create a DataFrame from List in Python | Pandas Tutorial for BeginnersJR: Educational Channel · 0:54 · 85 views
  9. Leetcode 2877 - How to transform a list in a dataframe [Pandas]Ptolémé · 1:45 · 37 views
  10. Create a Dataframe from List || Leetcode Pandas PracticeTechify Tutorials · 3:12 · 33 views

The problem

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.

Example 1:

Input:
student_data:
[
  [1, 15],
  [2, 11],
  [3, 11],
  [4, 20]
]
Output:
+------------+-----+
| student_id | age |
+------------+-----+
| 1          | 15  |
| 2          | 11  |
| 3          | 11  |
| 4          | 20  |
+------------+-----+
Explanation:
A DataFrame was created on top of student_data, with two columns named student_id and age.

Approach overview

Problem Overview: You are given a list of records and a set of column names. The task is to construct a tabular structure (a DataFrame) where each inner list represents a row and each value maps to its corresponding column. The goal is simply to transform the raw list structure into a structured table format.

Approach 1: Using pandas DataFrame Constructor (O(n) time, O(n) space)

In Python, the most direct solution uses the pandas library. The pd.DataFrame() constructor accepts a list of rows and a list of column names, then internally builds the tabular structure. Each inner list becomes a row and values are aligned with the provided column labels. The constructor performs a linear pass over the data, giving O(n) time complexity where n is the total number of elements across rows. This approach is preferred when working in data science or analytics environments where pandas is already part of the workflow.

Approach 2: Manual Construction using Native Arrays/Lists (O(n) time, O(n) space)

Languages without a built-in DataFrame abstraction (C, C++, Java, C#, JavaScript) require constructing the structure manually. Iterate through the input list and store each row in a 2D array or list-of-lists structure. Column names can be stored separately in an array or mapped to indices using a dictionary if column lookup is required. The algorithm performs a simple iteration over the dataset and copies values into the resulting structure. Because every element is processed once, the time complexity is O(n) and the additional memory required is also O(n).

This approach mirrors how tabular data is internally represented in many systems: rows stored sequentially with columns mapped by index. It is common when implementing lightweight table structures or when solving problems involving arrays and basic data processing.

Recommended for interviews: Interviewers usually expect the straightforward construction logic rather than heavy library usage. Showing the manual list/array construction demonstrates you understand how tabular data structures work internally. The pandas solution is still useful in Python-centric environments because it leverages a standard library designed for data manipulation.

Approach 1: Using pandas library in Python

This approach utilizes the Python pandas library, which is specifically designed for data manipulation and analysis. We will simply pass the list to the DataFrame constructor along with column labels.

import pandas as pd

def create_dataframe(student_data):
    df = pd.DataFrame(student_data, columns=['student_id', 'age'])
    return df

# Example usage
student_data = [[1, 15], [2, 11], [3, 11], [4, 20]]
print(create_dataframe(student_data))

This solution uses the pandas library to create a DataFrame. We call the DataFrame constructor with the 2D list and specify the column names. The returned DataFrame has the desired structure.

Complexity

Time Complexity: O(n) where n is the number of rows in the student_data list.
Space Complexity: O(n) as the data is stored in a DataFrame.

Try this approach in the editor

Approach 2: Manual Construction using Native Lists/Arrays

This method manually constructs a DataFrame-like structure using native programming constructs like lists, arrays, dictionaries, etc. This involves manually setting up structures to represent columns and rows and maintaining the desired format.

import java.util.ArrayList;
import java.util.List;

public class DataFrame {
    public static void printDataFrame(List<int[]> student_data) {
        System.out.println("+------------+-----+");
        System.out.println("| student_id | age |");
        System.out.println("+------------+-----+");
        for (int[] row : student_data) {
            System.out.format("| %10d | %3d |\n", row[0], row[1]);
        }
        System.out.println("+------------+-----+");
    }

    public static void main(String[] args) {
        List<int[]> student_data = new ArrayList<>();
        student_data.add(new int[]{1, 15});
        student_data.add(new int[]{2, 11});
        student_data.add(new int[]{3, 11});
        student_data.add(new int[]{4, 20});
        printDataFrame(student_data);
    }
}
#include <iostream>
#include <vector>

using namespace std;

void printDataFrame(const vector<vector<int>>& student_data) {
    cout << "+------------+-----+\n";
    cout << "| student_id | age |\n";
    cout << "+------------+-----+\n";
    for (const auto& row : student_data) {
        printf("| %10d | %3d |\n", row[0], row[1]);
    }
    cout << "+------------+-----+\n";
}

int main() {
    vector<vector<int>> student_data = {{1, 15}, {2, 11}, {3, 11}, {4, 20}};
    printDataFrame(student_data);
    return 0;
}
function printDataFrame(student_data) {
    console.log('+------------+-----+');
    console.log('| student_id | age |');
    console.log('+------------+-----+');
    student_data.forEach(row => {
        console.log(`| ${row[0].toString().padStart(10)} | ${row[1].toString().padStart(3)} |`);
    });
    console.log('+------------+-----+');
}

const student_data = [
    [1, 15],
    [2, 11],
    [3, 11],
    [4, 20]
];

printDataFrame(student_data);
#include <stdio.h>
#define ROWS 4

void printDataFrame(int student_data[ROWS][2]) {
    printf("+------------+-----+\n");
    printf("| student_id | age |\n");
    printf("+------------+-----+\n");
    for (int i = 0; i < ROWS; ++i) {
        printf("| %10d | %3d |\n", student_data[i][0], student_data[i][1]);
    }
    printf("+------------+-----+\n");
}

int main() {
    int student_data[ROWS][2] = {{1, 15}, {2, 11}, {3, 11}, {4, 20}};
    printDataFrame(student_data);
    return 0;
}
using System;
using System.Collections.Generic;

public class Program
{
    public static void PrintDataFrame(List<int[]> studentData)
    {
        Console.WriteLine("+------------+-----+");
        Console.WriteLine("| student_id | age |");
        Console.WriteLine("+------------+-----+");
        foreach (int[] row in studentData)
        {
            Console.WriteLine("| {0,10} | {1,3} |", row[0], row[1]);
        }
        Console.WriteLine("+------------+-----+");
    }

    public static void Main()
    {
        List<int[]> studentData = new List<int[]>
        {
            new int[] {1, 15},
            new int[] {2, 11},
            new int[] {3, 11},
            new int[] {4, 20}
        };
        PrintDataFrame(studentData);
    }
}

In this Java solution, an ArrayList of integer arrays is used to hold the student data. A static method printDataFrame prints the data in the desired format.

Complexity

Time Complexity: O(n), where n is the number of rows.
Space Complexity: O(1) as it handles printing directly.

Try this approach in the editor

Complexity comparison

ApproachComplexity
Using pandas library in Python

Time Complexity: O(n) where n is the number of rows in the student_data list.
Space Complexity: O(n) as the data is stored in a DataFrame.

Manual Construction using Native Lists/Arrays

Time Complexity: O(n), where n is the number of rows.
Space Complexity: O(1) as it handles printing directly.

Complexity analysis

ApproachTimeSpaceWhen to Use
pandas DataFrame Constructor (Python)O(n)O(n)When working in Python data analysis environments where pandas is available
Manual Construction with Arrays/ListsO(n)O(n)General approach for languages without DataFrame support such as C, C++, Java, C#, or JavaScript

Frequently asked questions

Is Create a DataFrame from List easy or hard?

Create a DataFrame from List is classified as an easy problem. The task mainly tests understanding of tabular data representation and basic list or array manipulation, with an O(n) construction algorithm.

Create a DataFrame from List Python/Java solution

In Python, the typical solution is pd.DataFrame(data, columns=columns) from the pandas library, which converts the list directly into a DataFrame. In Java or similar languages, create a List<List<T>> or 2D array and store rows manually while keeping column names in a separate array or map.

How to solve Create a DataFrame from List in O(n)?

Iterate through the input list once and map each row into a structured table. In Python, use pandas with pd.DataFrame(data, columns=column_names), which internally processes the dataset in linear time. In other languages, store rows in a 2D array or list structure while assigning column positions by index.

What is the best approach for Create a DataFrame from List?

The best approach depends on the language. In Python, the pandas DataFrame constructor is the most efficient and concise because it directly converts a list of rows into a structured table in O(n) time. In languages without pandas, the standard solution is to manually build a 2D array or list-of-lists while mapping column names to indices.

Is Create a DataFrame from List asked at Google/Amazon/Meta?

This problem reflects common data transformation tasks seen in data engineering and analytics interviews. Variations appear in companies that evaluate Python or data manipulation skills, particularly roles involving pandas, ETL pipelines, or structured data processing.

What data structure is used in Create a DataFrame from List?

The underlying structure is essentially a 2D array or list-of-lists where each inner list represents a row. Column names are stored separately and mapped to indices. Libraries like pandas wrap this structure with additional indexing and vectorized operations.

What is the time complexity of Create a DataFrame from List?

The time complexity is O(n), where n is the total number of elements across all rows in the input list. Each value must be processed once when building the DataFrame or copying elements into a 2D array structure. Space complexity is also O(n) because the resulting table stores all elements.

Comments

Now write it yourselfClose this page and solve Create a DataFrame from List in the editor, without looking.
Practise Create a DataFrame from List