How to rename column names in Pandas?

To rename column names in a Pandas DataFrame, you can use the following methods:

1. Rename Specific Columns with rename()

Use a dictionary to map old column names to new column names. This method is flexible and allows renaming specific columns.

python

import pandas as pd

df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})

# Rename columns "A" to "X" and "B" to "Y"
df = df.rename(columns={"A": "X", "B": "Y"})
print(df.columns)  # Output: Index(['X', 'Y'], dtype='object')

Key parameters:

  • columns: A dictionary of {old_name: new_name} pairs.
  • inplace=False: Set to True to modify the DataFrame in-place (instead of returning a copy).

2. Replace All Column Names

Directly assign a new list to df.columns. Ensure the list length matches the number of columns.

python

df.columns = ["X", "Y"]  # Rename all columns in order
print(df.columns)  # Output: Index(['X', 'Y'], dtype='object')

3. Rename Columns While Reading Data

Modify column names during file import (e.g., CSV, Excel):

python

df = pd.read_csv("data.csv", names=["X", "Y"], header=0)  # Replace headers

4. Clean Column Names Programmatically

Use string operations to standardize names (e.g., lowercase, replace spaces):

python

# Convert to lowercase and replace spaces with underscores
df.columns = df.columns.str.lower().str.replace(" ", "_")

Example Workflow

python

# Sample DataFrame
df = pd.DataFrame({
    "First Name": ["Alice", "Bob"],
    "Age (Years)": [25, 30]
})

# Rename specific columns
df = df.rename(columns={
    "First Name": "name",
    "Age (Years)": "age"
})

# Clean remaining columns (if any)
df.columns = df.columns.str.lower()
print(df.columns)  # Output: Index(['name', 'age'], dtype='object')

Key Notes:

  • Partial Renaming: With rename(), you only need to specify columns you want to change.
  • Error Handling: If a column name in the dictionary doesn’t exist, Pandas ignores it (no error).
  • Performance: Use inplace=True to avoid creating a copy of the DataFrame.

Choose the method that best fits your use case—whether you need precise control or bulk renaming!

Leave a Reply

Your email address will not be published. Required fields are marked *