Friday 8 December 2023

Pandas: rename row labels of DataFrame

Using rename method, we can change the row labels.

Following snippet change the name of row label 'Krishna' to 'Ram' and  'Sailu' to  'Harika'

 

new_names = {'Krishna': 'Ram', 'Sailu': 'Harika'}

df.rename(new_names, axis=0, inplace=True )

 

Find the below working application.

 

rename_row_labels.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu'],
        'Age': [34, 35, 29, 35],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female'],
        'Rating': [81, 76, 67, 100]}

df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

print('\nSet "Name" column as index column')
df.set_index('Name', inplace=True)
print(df)

print('\nRenaming the user names')
new_names = {'Krishna': 'Ram', 'Sailu': 'Harika'}
df.rename(new_names, axis=0, inplace=True )
print(df)

 

Output

Original DataFrame
      Name  Age       City  Gender  Rating
0  Krishna   34  Bangalore    Male      81
1    Sailu   35  Hyderabad  Female      76
2     Joel   29  Hyderabad    Male      67
3    Chamu   35    Chennai  Female     100

Set "Name" column as index column
         Age       City  Gender  Rating
Name                                   
Krishna   34  Bangalore    Male      81
Sailu     35  Hyderabad  Female      76
Joel      29  Hyderabad    Male      67
Chamu     35    Chennai  Female     100

Renaming the user names
        Age       City  Gender  Rating
Name                                  
Ram      34  Bangalore    Male      81
Harika   35  Hyderabad  Female      76
Joel     29  Hyderabad    Male      67
Chamu    35    Chennai  Female     100

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment