Difficulty: Easy | Acceptance: 81.00% | Paid: No Topics: N/A
You are given a 2D integer array student_data where student_data[i] represents the data for the ith student. The data for each student is represented as [student_id, age].
Return a pandas DataFrame with columns student_id and age containing the data from student_data.
- Table of Contents
- Examples
- Constraints
- Direct DataFrame Construction
- Dictionary Conversion Approach
- List of Dictionaries Approach
Examples
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.
Constraints
1 <= student_data.length <= 10⁵
student_data[i].length == 2
1 <= student_data[i][0] <= 10⁹
1 <= student_data[i][1] <= 100
Direct DataFrame Construction
Intuition Use pandas DataFrame constructor directly by passing the 2D list as data and specifying column names.
Steps
- Import pandas library
- Create DataFrame using pd.DataFrame() with student_data and columns parameter
- Return the DataFrame
import pandas as pd
def createDataFrame(student_data):
return pd.DataFrame(student_data, columns=['student_id', 'age'])Complexity
- Time: O(n) where n is the number of rows
- Space: O(n) for storing the DataFrame
- Notes: Most efficient and idiomatic pandas approach
Dictionary Conversion Approach
Intuition Convert the 2D list into a dictionary format where keys are column names and values are lists of data for each column.
Steps
- Extract student_id values from each row into a list
- Extract age values from each row into a list
- Create a dictionary with column names as keys
- Pass dictionary to pd.DataFrame()
import pandas as pd
def createDataFrame(student_data):
student_ids = [row[0] for row in student_data]
ages = [row[1] for row in student_data]
data_dict = {'student_id': student_ids, 'age': ages}
return pd.DataFrame(data_dict)Complexity
- Time: O(n) where n is the number of rows
- Space: O(n) for storing intermediate lists and DataFrame
- Notes: More verbose but useful when data comes from different sources
List of Dictionaries Approach
Intuition Convert each row into a dictionary with column names as keys, then create DataFrame from list of dictionaries.
Steps
- Iterate through each row in student_data
- Create a dictionary for each row mapping column names to values
- Collect all dictionaries into a list
- Pass list of dictionaries to pd.DataFrame()
import pandas as pd
def createDataFrame(student_data):
data = [{'student_id': row[0], 'age': row[1]} for row in student_data]
return pd.DataFrame(data)Complexity
- Time: O(n) where n is the number of rows
- Space: O(n) for storing list of dictionaries and DataFrame
- Notes: Useful when dealing with JSON-like data structures