Problem

DataFrame df1 +————-+——–+ | Column Name | Type | +————-+——–+ | student_id | int | | name | object | | age | int | +————-+——–+

DataFrame df2 +————-+——–+ | Column Name | Type | +————-+——–+ | student_id | int | | name | object | | age | int | +————-+——–+

Write a solution to concatenate these two DataFrames vertically into one DataFrame.

The result format is in the following example.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
**Input:
df1**
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 1          | Mason   | 8   |
| 2          | Ava     | 6   |
| 3          | Taylor  | 15  |
| 4          | Georgia | 17  |
+------------+---------+-----+
**df2** +------------+------+-----+
| student_id | name | age |
+------------+------+-----+
| 5          | Leo  | 7   |
| 6          | Alex | 7   |
+------------+------+-----+
Output:
+------------+---------+-----+
| student_id | name    | age |
+------------+---------+-----+
| 1          | Mason   | 8   |
| 2          | Ava     | 6   |
| 3          | Taylor  | 15  |
| 4          | Georgia | 17  |
| 5          | Leo     | 7   |
| 6          | Alex    | 7   |
+------------+---------+-----+
Explanation: The two DataFramess are stacked vertically, and their rows are combined.

## Solution

### Method 1 - Pandas Concat

#### Intuition
To stack two DataFrames vertically, use pandas' `concat` function.

#### Approach
Call `pd.concat([df1, df2], ignore_index=True)` to combine the rows.

#### Code

1
2
def concatenate_dataframes(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
    return pd.concat([df1, df2], ignore_index=True)
#### Complexity * Time complexity: `O(n)` where n is the total number of rows. * 🧺 Space complexity: `O(n)` for the output DataFrame.