Skip to content

Instantly share code, notes, and snippets.

@sreekarun
Last active April 5, 2026 13:48
Show Gist options
  • Select an option

  • Save sreekarun/38e87ce21795a61dab73ecdbc4a930a9 to your computer and use it in GitHub Desktop.

Select an option

Save sreekarun/38e87ce21795a61dab73ecdbc4a930a9 to your computer and use it in GitHub Desktop.
Pandas notes

Renaming Columns & DataFrames in Pandas


1. Rename Specific Columns — rename()

import pandas as pd

df = pd.DataFrame({
    'us_citizen': ['Y', 'N', 'Y'],
    'pell_recipient': ['N', 'Y', 'Y'],
    'gpa': [3.5, 2.8, 3.9]
})

# Rename specific columns using a dict
df = df.rename(columns={
    'us_citizen': 'is_citizen',
    'pell_recipient': 'has_pell'
})

Result:

is_citizen has_pell gpa
Y N 3.5
N Y 2.8
Y Y 3.9

2. Rename All Columns at Once — reassign .columns

# Useful when you want to replace all column names in order
df.columns = ['citizen', 'pell', 'grade_point']

⚠️ The number of names must match the number of columns exactly.


3. Rename with a Function — apply a transformation to all column names

# Lowercase all column names
df.columns = df.columns.str.lower()

# Replace spaces with underscores (common after reading messy CSVs)
df.columns = df.columns.str.replace(' ', '_')

# Strip whitespace and lowercase in one step
df.columns = df.columns.str.strip().str.lower()

4. Rename Using rename() with a Function

# Add a prefix to all columns
df = df.rename(columns=lambda c: 'student_' + c)

# Uppercase all column names
df = df.rename(columns=str.upper)

Result of prefix example:

student_citizen student_pell student_grade_point
Y N 3.5

5. Rename the DataFrame Index

# Rename the index labels
df = df.rename(index={0: 'row_a', 1: 'row_b', 2: 'row_c'})

# Rename the index name itself
df.index.name = 'student_id'

6. Rename After a GroupBy / Aggregation

summary = df.groupby('major').agg(
    avg_gpa=('gpa', 'mean'),       # new_name=(column, func)
    student_count=('gpa', 'count')
)

This is the cleanest way to rename aggregated columns inline — no separate .rename() needed.


7. Rename a DataFrame Variable (reassignment)

# "Renaming" a DataFrame is just reassigning to a new variable
students_df = df                    # alias (same object)
students_df = df.copy()             # independent copy with new name

🧠 Quick Reference

Goal Method
Rename specific columns df.rename(columns={'old': 'new'})
Rename all columns df.columns = [...]
Lowercase all names df.columns.str.lower()
Add prefix/suffix df.rename(columns=lambda c: 'pfx_' + c)
Rename during groupby agg(new_name=('col', 'func'))
Rename index df.rename(index={0: 'a'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment