Rename Columns - Problem
You are given a pandas DataFrame containing student information with the following columns: id, first, last, and age.
Your task is to rename these columns to make them more descriptive and follow a consistent naming convention:
id→student_idfirst→first_namelast→last_nameage→age_in_years
This is a common data preprocessing task when working with datasets that have abbreviated or unclear column names. Good column naming is crucial for data clarity and maintainability!
Input & Output
example_1.py — Basic Student Data
$
Input:
students = pd.DataFrame({
'id': [1, 2, 3],
'first': ['Alice', 'Bob', 'Charlie'],
'last': ['Johnson', 'Smith', 'Davis'],
'age': [20, 21, 19]
})
›
Output:
student_id first_name last_name age_in_years
0 1 Alice Johnson 20
1 2 Bob Smith 21
2 3 Charlie Davis 19
💡 Note:
All four columns are successfully renamed according to the mapping: id→student_id, first→first_name, last→last_name, age→age_in_years
example_2.py — Single Student Record
$
Input:
students = pd.DataFrame({
'id': [1001],
'first': ['Emma'],
'last': ['Watson'],
'age': [22]
})
›
Output:
student_id first_name last_name age_in_years
0 1001 Emma Watson 22
💡 Note:
Even with a single row, the column renaming works exactly the same way - only the headers change, data remains intact
example_3.py — Empty DataFrame Edge Case
$
Input:
students = pd.DataFrame({
'id': [],
'first': [],
'last': [],
'age': []
})
›
Output:
Empty DataFrame
Columns: [student_id, first_name, last_name, age_in_years]
Index: []
💡 Note:
Column renaming works even on empty DataFrames - the structure is preserved with new column names, just no data rows
Visualization
Tap to expand
Understanding the Visualization
1
Original DataFrame Structure
DataFrame with abbreviated column names that need clarification
2
Create Column Mapping
Define a dictionary mapping old names to more descriptive new names
3
Apply rename() Method
Use pandas built-in rename() function with the mapping dictionary
4
Headers Updated Efficiently
Only column headers change - data stays in place with no copying overhead
Key Takeaway
🎯 Key Insight: Column renaming is a metadata operation that only changes headers, making it extremely efficient for any DataFrame size.
Time & Space Complexity
Time Complexity
O(1)
Only column headers are modified, data is not copied
✓ Linear Growth
Space Complexity
O(1)
No additional space needed, columns renamed in place
✓ Linear Space
Constraints
-
DataFrame will always have exactly 4 columns:
id,first,last,age - Number of rows can be 0 ≤ n ≤ 103
- Column names must be renamed exactly as specified
- Data types and values should remain unchanged
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code