Rename column by index in Pandas

Rename column by index in Pandas

In order to rename a column by its index in a Pandas DataFrame, you can use the .columns attribute to get the current column names, modify the list, and then reassign it back.

Here's how you can rename a column by its index:

import pandas as pd # Sample dataframe df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) print("Original DataFrame:") print(df) # Rename the second column (index 1) to 'X' cols = df.columns.tolist() cols[1] = 'X' df.columns = cols print("\nDataFrame after renaming:") print(df) 

Output:

Original DataFrame: A B C 0 1 4 7 1 2 5 8 2 3 6 9 DataFrame after renaming: A X C 0 1 4 7 1 2 5 8 2 3 6 9 

In the example above, the column with index 1 (i.e., column 'B') was renamed to 'X'.


More Tags

file-io encode image-rotation momentjs network-programming deadlock laravel-excel vuforia ssh-tunnel nfs

More Programming Guides

Other Guides

More Programming Examples