Skip to content

2885. Rename Columns

DataFrame students

Column NameType
idint
firstobject
lastobject
ageint

Instructions

  • 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.

Example

Input:

idfirstlastage
1MasonKing6
2AvaWright7
3TaylorHall16
4GeorgiaThompson18
5ThomasMoore10

Output:

student_idfirst_namelast_nameage_in_years
1MasonKing6
2AvaWright7
3TaylorHall16
4GeorgiaThompson18
5ThomasMoore10

Explanation:

The column names are changed accordingly.

Submissions

python
import pandas as pd

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

Explanation

Python (Pandas)
Submitted by @noeyislearning
  • import pandas as pd: Import the pandas library to work with DataFrames.
  • def renameColumns(students: pd.DataFrame) -> pd.DataFrame:: Define a function called renameColumns that takes a DataFrame students as input and returns a DataFrame.
  • return students.rename(columns={...}): Rename the columns of the DataFrame using a dictionary where the keys are the original column names and the values are the new column names.