How to rename multiple column headers in a Pandas DataFrame?

How to rename multiple column headers in a Pandas DataFrame?

To rename multiple column headers in a Pandas DataFrame, you can use the rename method. The columns to be renamed can be specified using a dictionary where the keys are the current column names and the values are the new column names.

Here's a quick example to illustrate this:

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

This will produce:

 X Y C 0 1 4 7 1 2 5 8 2 3 6 9 

Note that you can also use the inplace parameter if you don't want to reassign the modified DataFrame:

df.rename(columns={'A': 'X', 'B': 'Y'}, inplace=True) 

Using this approach, you can rename as many columns as needed by adding more key-value pairs to the dictionary provided to the columns parameter.


More Tags

prettier negative-lookbehind ios7 dispose polymer ora-01017 real-time graph wordpress-json-api wix

More Programming Guides

Other Guides

More Programming Examples