Friday, 8 December 2023

Pandas: rename the column names of dataframe using .columns property

By setting .columns property explicitly we can rename the column names.

 For example, let’s consider below data set.

      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

 

I would like to rename the column

a.   Name to User_Name

b.   Rating to User_Rating

 

Following snippet do the work for us.

df.columns = ['User_Name', 'Age', 'City', 'Gender', 'User_Rating']

 

Find the below working application.

change_column_names.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)

df.columns = ['User_Name', 'Age', 'City', 'Gender', 'User_Rating']
print('\nDataFrame after renaming the columns')
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

DataFrame after renaming the columns
  User_Name  Age       City  Gender  User_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


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment