Reshape Data: Concatenate - Problem

You are given two DataFrames with identical structure:

DataFrame df1

Column NameType
student_idint
nameobject
ageint

DataFrame df2

Column NameType
student_idint
nameobject
ageint

Write a function to concatenate these two DataFrames vertically into one DataFrame. The rows from df2 should be appended below the rows from df1.

Return the concatenated DataFrame.

Input & Output

Example 1 — Basic Concatenation
$ Input: df1 = [{"student_id": 1, "name": "Alice", "age": 20}, {"student_id": 2, "name": "Bob", "age": 22}], df2 = [{"student_id": 3, "name": "Charlie", "age": 19}, {"student_id": 4, "name": "Diana", "age": 21}]
Output: [{"student_id": 1, "name": "Alice", "age": 20}, {"student_id": 2, "name": "Bob", "age": 22}, {"student_id": 3, "name": "Charlie", "age": 19}, {"student_id": 4, "name": "Diana", "age": 21}]
💡 Note: All rows from df1 come first, followed by all rows from df2, maintaining original order within each DataFrame
Example 2 — Single Row DataFrames
$ Input: df1 = [{"student_id": 1, "name": "Eve", "age": 23}], df2 = [{"student_id": 2, "name": "Frank", "age": 24}]
Output: [{"student_id": 1, "name": "Eve", "age": 23}, {"student_id": 2, "name": "Frank", "age": 24}]
💡 Note: Each DataFrame has only one row, result combines both into a two-row DataFrame
Example 3 — Empty DataFrame
$ Input: df1 = [{"student_id": 5, "name": "Grace", "age": 20}], df2 = []
Output: [{"student_id": 5, "name": "Grace", "age": 20}]
💡 Note: When one DataFrame is empty, result contains only rows from the non-empty DataFrame

Constraints

  • Both DataFrames have identical column structure
  • 0 ≤ number of rows in each DataFrame ≤ 1000
  • Column names are consistent across both DataFrames

Visualization

Tap to expand
Reshape Data: Concatenate INPUT df1 student_id name age 1 Alice 20 2 Bob 22 df2 student_id name age 3 Charlie 19 4 Diana 21 Both DataFrames have identical structure df1 df2 ALGORITHM STEPS 1 Import pandas import pandas as pd 2 Create DataFrames df1, df2 from input 3 Use pd.concat() pd.concat([df1, df2]) 4 Reset index ignore_index=True df1 + df2 df1 rows df2 rows FINAL RESULT Combined DataFrame student_id name age 1 Alice 20 2 Bob 22 3 Charlie 19 4 Diana 21 from df1 from df2 def concatenate (df1,df2): return pd.concat( [df1,df2], ignore_index =True) OK - 4 rows combined Vertically stacked 2 rows from df1 2 rows from df2 Key Insight: pd.concat() stacks DataFrames vertically (axis=0 by default). Use ignore_index=True to reset the index from 0. Both DataFrames must have identical column structure for vertical concatenation. TutorialsPoint - Reshape Data: Concatenate | Built-in Concatenation
Asked in
Meta 15 Google 12
12.5K Views
High Frequency
~5 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen