Need to rename columns in Pandas DataFrame?
If so, you may use the following syntax to rename your column:
df = df.rename(columns = {'old column name':'new column name'})
In the next section, you’ll see 2 examples of renaming:
- Single Column in Pandas DataFrame
- Multiple Columns in Pandas DataFrame
Example 1: Rename a Single Column in Pandas DataFrame
Let’s say that you created a DataFrame in Python, but assigned the wrong column name.
For example, let’s suppose that you originally assigned the column name of ‘Vegetables’ but the items under that column are actually Fruits!
Here is the code to create the DataFrame with the ‘Vegetables’ column name:
import pandas as pd data = {'Vegetables': ['Apple', 'Orange', 'Banana', 'Coconut', 'Mango']} df = pd.DataFrame(data, columns = ['Vegetables']) print (df)
And here is the result:
Vegetables
0 Apple
1 Orange
2 Banana
3 Coconut
4 Mango
Realizing that you assigned the wrong column name, you decided to rename the column from ‘Vegetables’ to ‘Fruits.’
This is the code that you may then use to rename the column:
import pandas as pd data = {'Vegetables': ['Apple', 'Orange', 'Banana', 'Coconut', 'Mango']} df = pd.DataFrame(data, columns = ['Vegetables']) df = df.rename(columns = {'Vegetables':'Fruits'}) print (df)
As you can see, the column name is now ‘Fruits’:
Fruits
0 Apple
1 Orange
2 Banana
3 Coconut
4 Mango
Example 2: Rename Multiple Columns in Pandas DataFrame
Now what if you want rename multiple columns in your Pandas DataFrame?
For example, let’s say that you originally assigned the wrong column names for two columns in your DataFrame:
- The column name of ‘Colors’ contained a list of shapes
- The column name of ‘Shapes’ contained a list of colors
This is how the DataFrame looks like:
import pandas as pd data = {'Colors': ['Triangle', 'Square', 'Circle'], 'Shapes': ['Red', 'Blue', 'Green'] } df = pd.DataFrame(data,columns = ['Colors','Shapes']) print (df)
And this is the result:
Colors Shapes
0 Triangle Red
1 Square Blue
2 Circle Green
The concept to rename multiple columns in Pandas DataFrame is similar to that under example one. You just need to separate the renaming of each column using a comma:
df = df.rename(columns = {'Colors':'Shapes','Shapes':'Colors'})
So this is the full Python code to rename the columns:
import pandas as pd data = {'Colors': ['Triangle', 'Square', 'Circle'], 'Shapes': ['Red', 'Blue', 'Green'] } df = pd.DataFrame(data,columns = ['Colors','Shapes']) df = df.rename(columns = {'Colors':'Shapes','Shapes':'Colors'}) print (df)
You’ll now get the correct column names:
Shapes Colors
0 Triangle Red
1 Square Blue
2 Circle Green