Renaming Columns in Python pandas
Premium
Changing column names in a pandas DataFrame is a common task, often done to make data more readable, comply with naming conventions, or prepare for data processing steps. Column names can be changed using the rename method or by directly assigning a new list of column names to the columns attribute of the DataFrame. The rename method is more flexible as it allows you to rename only specific columns without needing to specify all column names.
Here's an example showing how to rename columns in a DataFrame:
1# Rename columns using the 'rename' method
2loan_data_cleaned = loan_data_cleaned.rename(columns={
3 'CustomerName': 'ClientName',
4 'LoanAmount': 'Amount',
5 'LoanStartDate': 'StartDate',
6 'LoanEndDate': 'EndDate'
7})
8
9# Alternatively, to rename all columns directly:
10# loan_data_cleaned.columns = ['NewCol1', 'NewCol2', 'NewCol3', ..., 'NewColN']
11
12# Verify the changes
13print(loan_data_cleaned.columns)
14
15
