#2877
Create a DataFrame from List
EasyArrayDataFrame
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using pandas directly to create a DataFrame from the 2D list is the most efficient way. This leverages built-in functions that are optimized for performance.
⚙️
Algorithm
2 steps- 1Step 1: Use the pandas DataFrame constructor directly with the 2D list.
- 2Step 2: Specify the column names as a parameter.
solution.py6 lines
1# Full working Python code
2import pandas as pd
3
4student_data = [[1, 15], [2, 11], [3, 11], [4, 20]]
5df = pd.DataFrame(student_data, columns=['student_id', 'age'])
6print(df)ℹ
Complexity note: This solution is O(n) because it processes the list in a single pass without needing to append repeatedly.
- 1Using built-in functions can greatly simplify your code.
- 2Understanding the underlying data structure helps in optimizing performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.