#2888
Reshape Data: Concatenate
EasyDataFrame ManipulationConcatenationData Aggregation
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)
The optimal approach leverages built-in functions in pandas to concatenate the DataFrames efficiently. This is much faster and cleaner than manually iterating through rows.
⚙️
Algorithm
2 steps- 1Step 1: Use the pandas concat function to combine df1 and df2.
- 2Step 2: Specify the axis parameter as 0 to concatenate vertically.
solution.py7 lines
1import pandas as pd
2
3df1 = pd.DataFrame({'student_id': [1, 2, 3, 4], 'name': ['Mason', 'Ava', 'Taylor', 'Georgia'], 'age': [8, 6, 15, 17]})
4df2 = pd.DataFrame({'student_id': [5, 6], 'name': ['Leo', 'Alex'], 'age': [7, 7]})
5
6result = pd.concat([df1, df2], axis=0).reset_index(drop=True)
7print(result)ℹ
Complexity note: The time complexity is O(n) because we are simply concatenating the two DataFrames in one pass, which is efficient.
- 1Using built-in functions for DataFrame operations is usually more efficient than manual iterations.
- 2Understanding the axis parameter in pandas is crucial for manipulating DataFrames correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.