We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Rename Columns

Difficulty: Easy


Problem Description

You are given a DataFrame students with the following columns: id, first, last, and age. Your task is 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 should be a DataFrame with the renamed columns.


Key Insights

  • Understanding how to manipulate DataFrame column names is crucial for data preprocessing.
  • Renaming columns is a common operation in data analysis and database management.
  • Familiarity with DataFrame operations can enhance your ability to work with large datasets.

Space and Time Complexity

Time Complexity: O(n), where n is the number of rows in the DataFrame, as each row needs to be traversed to create the new DataFrame. Space Complexity: O(1) if we ignore the output DataFrame space, as we are only renaming the columns in place.


Solution

To solve this problem, we will use a DataFrame manipulation approach. The primary data structure is a DataFrame, which allows for easy access and modification of column names. The algorithm involves creating a mapping of the old column names to the new column names and then applying this mapping to rename the columns.

  1. Create a dictionary that maps old column names to new column names.
  2. Use the DataFrame's rename method to apply this mapping.
  3. Return the modified DataFrame.

Code Solutions

import pandas as pd

# Sample DataFrame creation
data = {
    'id': [1, 2, 3, 4, 5],
    'first': ['Mason', 'Ava', 'Taylor', 'Georgia', 'Thomas'],
    'last': ['King', 'Wright', 'Hall', 'Thompson', 'Moore'],
    'age': [6, 7, 16, 18, 10]
}
students = pd.DataFrame(data)

# Renaming columns
students.rename(columns={
    'id': 'student_id',
    'first': 'first_name',
    'last': 'last_name',
    'age': 'age_in_years'
}, inplace=True)

# Display the result
print(students)
← Back to All Questions