Renaming columns in pandas is a common task when working with data, and pandas makes it easy to do. Here are a few methods to rename columns in a pandas DataFrame, with examples for each.
Method 1: Using rename()
Function
The rename()
function is the most flexible way to rename columns. You can use it to rename a specific column or multiple columns at once.
Example: Renaming a Single Column
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# Renaming column 'A' to 'Column1'
df = df.rename(columns={'A': 'Column1'})
print(df)
Output:
Column1 B
0 1 4
1 2 5
2 3 6
Example: Renaming Multiple Columns
# Renaming columns 'A' to 'Column1' and 'B' to 'Column2'
df = df.rename(columns={'A': 'Column1', 'B': 'Column2'})
print(df)
Output:
Copy code
Column1 Column2
0 1 4
1 2 5
2 3 6
Method 2: Using columns
Attribute
If you want to rename all columns at once, you can directly assign a new list to the columns
attribute of the DataFrame.
Example: Renaming All Columns
# Renaming all columns
df.columns = ['X', 'Y']
print(df)
Output:
X Y
0 1 4
1 2 5
2 3 6
Method 3: Using List Comprehension
If you want to apply a function or transformation to all column names, you can use list comprehension.
Example: Converting All Column Names to Lowercase
# Converting all column names to lowercase
df.columns = [col.lower() for col in df.columns]
print(df)
Output:
column1 column2
0 1 4
1 2 5
2 3 6
Summary
rename()
Function: Best for renaming specific columns, offers flexibility.columns
Attribute: Quick way to rename all columns at once.- List Comprehension: Useful for applying transformations to all column names.
These methods give you the flexibility to rename columns in a way that best suits your data manipulation needs.
Discussion