In this post, I am going to explain how to rename the column labels in a DataFrame.
Example
new_column_names = {'Name': 'User_Name', 'City': 'User_City'}
df = df.rename(columns=new_column_names)
Above snippet rename the column
a. 'Name' to 'User_Name'
b. 'City' to 'User_City'
rename_columns.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('\nRename the columns "Name" to "User_Name" and "City" to "User_City"')
new_column_names = {'Name': 'User_Name', 'City': 'User_City'}
df = df.rename(columns=new_column_names)
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 Rename the columns "Name" to "User_Name" and "City" to "User_City" User_Name Age User_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
No comments:
Post a Comment