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 |
# 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.
# 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()# 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 |
# 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'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.
# "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| 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'}) |