Python-Pandas : Rename columns dynamically without specifying the name of the index column using Python

Python Pandas @ Freshers.in

To rename columns dynamically without specifying the name of the index column, you can retrieve the index column name using the df.index.name attribute, and then use it to rename the columns. Here’s an example:

import pandas as pd
# Create a sample dataframe with columns containing dots
df = pd.DataFrame({'col.one': [1, 2, 3], 'col.two': [4, 5, 6]})
# Set the index to be the first column
df.set_index('col.one', inplace=True)
# Get the name of the index column
index_name = df.index.name
# Rename the columns dynamically
df.columns = [col.replace('.', '_') if col != index_name else col for col in df.columns]
# Display the updated dataframe
print(df)

Output

         col_two
col.one        
1              4
2              5
3              6

We use the df.index.name attribute to retrieve the name of the index column. Then, we use a list comprehension to rename the columns dynamically. We check if each column name is equal to the index column name, and if it is, we leave it unchanged. Otherwise, we replace dots with underscores. Finally, we assign the updated column names to the columns attribute of the dataframe and display the updated dataframe.

The index column name is ‘col.one’, which is automatically retrieved using the df.index.name attribute. This allows us to rename the columns dynamically without hard-coding the name of the index column.

Refer more on python here :

Author: user

Leave a Reply