Renaming Columns, Replacing Values & Sorting0%
Renaming Columns, Replacing Values & Sorting
Beginner12 min read•Updated: Jul 11, 2026
Renaming Columns, Replacing Values & Sorting
Reading Time: 8 Mins | Level: Beginner to Advanced
1. Renaming Columns & Index Labels (rename)
Often raw datasets come with messy column names containing spaces, typos, or special characters. Use df.rename():
Python
import pandas as pd
df = pd.DataFrame({
'emp id': [101, 102, 103],
'emp_name': ['Amit', 'Sunita', 'Karan'],
'sal': [50000, 75000, 62000]
})
# Renaming specific columns using a dictionary
df_renamed = df.rename(columns={
'emp id': 'Employee_ID',
'emp_name': 'Full_Name',
'sal': 'Salary_INR'
})
print(df_renamed)
Bulk Column Renaming (Sanitizing All Headers):
Python
# Clean all column names: lowercase and replace spaces with underscores
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_')
2. Replacing Values Across Columns (replace)
The .replace() method searches and replaces specific values across a Series or entire DataFrame:
Python
# Replace legacy department codes with full names
df['Department'] = df['Department'].replace({
'MKT': 'Marketing',
'FIN': 'Finance',
'ENG': 'Engineering'
})
3. Sorting Data in Pandas
A. Sorting by Column Values (sort_values)
Python
# Sort by Salary descending
df_sorted = df.sort_values(by='Salary_INR', ascending=False)
# Multi-column sorting: First by Department (Ascending), then by Salary (Descending)
df_multi_sort = df.sort_values(
by=['Department', 'Salary_INR'],
ascending=[True, False]
)
B. Sorting by Index Labels (sort_index)
After filtering or grouping operations, restore original sequential index ordering:
Python
df_restored = df.sort_index(ascending=True)
4. Inspecting Extremes: nlargest & nsmallest
Instead of sorting a 10-million row table just to find the top 5 earners, use the optimized nlargest() method:
Python
# Top 5 highest earners
top_5 = df.nlargest(5, 'Salary_INR')
# 3 lowest revenue products
bottom_3 = df.nsmallest(3, 'Revenue')
Interactive Quiz
Multiple Choice Questions
Question 1
Which parameter in
df.sort_values() determines whether sorting is lowest-to-highest or highest-to-lowest?Question 2
How can you rename the column
'old_col' to 'new_col' in a DataFrame?Question 3
Which method efficiently retrieves the top 10 highest rows based on a specific column without sorting the entire dataset?
Question 4
If you want to sort by 'Department' ascending and 'Salary' descending simultaneously, what syntax is used?
Question 5
What does
df.sort_index() do?Next Lesson
GroupBy Mechanics: Split-Apply-Combine
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Vectorized String Methods (.str accessor) | GroupBy Mechanics: Split-Apply-Combine |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.