2885 Rename Columns

Problem Statement

DataFrame students

Column Name
Type

id

int

first

object

last

object

age

int

Write a solution to rename the columns as follows:

  • id to student_id

  • first to first_name

  • last to last_name

  • age to age_in_years

  • The result format is in the following example.

For the whole problem statement, please refer here.

Plans

  • The DataFrame contains columns: id, first, last, and age.

  • We will rename the columns as follows:

    • id to student_id

    • first to first_name

    • last to last_name

    • age to age_in_years

  • Use the appropriate pandas function to rename the columns.

  • Return the Modified DataFrame

Solution

import pandas as pd

def renameColumns(students: pd.DataFrame) -> pd.DataFrame:
    # Rename the columns in the DataFrame
    renamed = students.rename(columns= {
        'id': 'student_id',
        'first': 'first_name',
        'last': 'last_name',
        'age': 'age_in_years'
    })

    # Return the DataFrame with the renamed columns
    return renamed

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 renameColumns that takes a single argument students, which is a DataFrame containing student data.

  3. Renaming Columns

    • We use the rename method on the DataFrame students to rename the columns as specified in the problem statement.

    • The columns argument is a dictionary where the keys are the current column names and the values are the new column names.

  4. Return the Result

    • We return the modified DataFrame with the renamed columns as specified in the problem statement.

Last updated