Change column names and row indexes in Pandas DataFrame

Change column names and row indexes in Pandas DataFrame

In pandas, changing column names and row indexes of a DataFrame is a common operation. Let's go through how to achieve both:

1. Changing Column Names:

a. Renaming Specific Columns:

You can rename specific columns using the rename method.

import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) # Rename columns df = df.rename(columns={'A': 'X', 'B': 'Y'}) print(df) 

b. Renaming All Columns:

If you want to rename all columns, you can simply assign a new list of column names to df.columns.

df.columns = ['X', 'Y'] print(df) 

2. Changing Row Indexes:

a. Renaming Specific Indexes:

You can rename specific row indexes using the rename method.

# Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }, index=['p', 'q', 'r']) # Rename indexes df = df.rename(index={'p': 'x', 'q': 'y'}) print(df) 

b. Replacing All Indexes:

If you want to replace all row indexes, you can assign a new list or Index object to df.index.

df.index = ['x', 'y', 'z'] print(df) 

Note:

When using the rename method, by default it returns a new DataFrame with the columns/indexes renamed. If you want to modify the original DataFrame in-place, you can use the inplace=True argument:

df.rename(columns={'A': 'X', 'B': 'Y'}, inplace=True) df.rename(index={'p': 'x', 'q': 'y'}, inplace=True) 

Always be cautious when using inplace=True, as it modifies the original data.


More Tags

jmx mpi flutter-image javac hex uicollectionviewcell unsafe figsize relational-database ssrs-tablix

More Programming Guides

Other Guides

More Programming Examples