2888 Reshape Data: Concatenate

Problem Statement

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.

For the whole problem statement, please refer here.

Plans

  • Use pandas to handle the data.

  • Concatenate the two DataFrames vertically.

  • Provide the concatenated DataFrame.

  • The resulting DataFrame should have the same columns as the input DataFrames.

Solution

import pandas as pd

def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame:
    # Concatenate df1 and df2
    return pd.concat([df1, df2], ignore_index=True)

Explanation

  1. Import Pandas

    • We start by importing the Pandas library, which provides data structures and operations for manipulating numerical tables and time series.

  2. Define the Function

    • We define a function concatenateTables that takes two arguments df1 and df2, which are DataFrames to be concatenated.

  3. Concatenating DataFrames

    • We use the pd.concat function to concatenate the two DataFrames df1 and df2 vertically.

    • The ignore_index=True argument is used to reset the index of the resulting DataFrame after concatenation.

  4. Return the Result

    • We return the concatenated DataFrame that contains the data from both input DataFrames vertically.

Last updated