Rename Columns
Sometimes, raw data may have less-than-ideal column names. In pandas, you can easily rename columns using the rename()
function. This function allows you to replace column and index names efficiently.
Usage
rename(mapper, axis)
:
- mapper: This parameter takes a dictionary where the keys represent the current column or index names, and the values represent the new names you want to assign.
- axis: This parameter determines whether you're renaming columns or indexes. Use
axis=0
oraxis='index'
to rename indexes, andaxis=1
oraxis='columns'
to rename columns.
This tutorial uses classic Iris dataset, which can be downloaded here Iris dataset.
import pandas as pddf = pd.read_csv('Iris.csv')
Current column names in the Iris data are: Id, SepalLengthCm, SepalWidthCm, PetalLengthCm, PetalWidthCm, Species
df.columns
Output:
Index(['Id', 'SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm', 'Species'],
dtype='object')
1. Rename One Column with rename()
Function
In this example, we'll rename the SepalLengthCm column to SepalLength. To do this, we'll pass a dictionary to the mapper
parameter with the current column name as the key and the desired new name as the value. Meanwhile, we'll set axis=columns
or axis=1
.
df.rename(mapper={'SepalLengthCm': 'SepalLength'}, axis='columns').head()
Output:
Id | SepalLength | SepalWidthCm | PetalLengthCm | PetalWidthCm | Species | |
---|---|---|---|---|---|---|
0 | 1 | 5.1 | 3.5 | 1.4 | 0.2 | Iris-setosa |
1 | 2 | 4.9 | 3.0 | 1.4 | 0.2 | Iris-setosa |
2 | 3 | 4.7 | 3.2 | 1.3 | 0.2 | Iris-setosa |
3 | 4 | 4.6 | 3.1 | 1.5 | 0.2 | Iris-setosa |
4 | 5 | 5.0 | 3.6 | 1.4 | 0.2 | Iris-setosa |
2. Rename Multiple Columns
To update multiple column names at once, we'll just need to include these columns in the dictionary and pass to the mapper
parameter.
df.rename(mapper={ 'SepalLengthCm': 'SepalLength', 'SepalWidthCm': 'SepalWidth', 'PetalLengthCm': 'PetalLength', 'PetalWidthCm': 'PetalWidth'}, axis=1).head()
Output:
Id | SepalLength | SepalWidth | PetalLength | PetalWidth | Species | |
---|---|---|---|---|---|---|
0 | 1 | 5.1 | 3.5 | 1.4 | 0.2 | Iris-setosa |
1 | 2 | 4.9 | 3.0 | 1.4 | 0.2 | Iris-setosa |
2 | 3 | 4.7 | 3.2 | 1.3 | 0.2 | Iris-setosa |
3 | 4 | 4.6 | 3.1 | 1.5 | 0.2 | Iris-setosa |
4 | 5 | 5.0 | 3.6 | 1.4 | 0.2 | Iris-setosa |
Great! Renaming a column becomes a breeze with the help of the rename()
function. Our next tutorial will delve into computing numerical statistics of columns.