Rename Column of pandas DataFrame by Index in Python (Example)


In this post you’ll learn how to change the names of pandas DataFrame columns by index positions in Python programming.

Table of contents:

Let’s take a look at some Python codes in action.


Example Data & Add-On Libraries

We first have to load the pandas library, if we want to apply the corresponding functions:

import pandas as pd                                         # Load pandas library

We’ll also have to create some example data:

data = pd.DataFrame({'x1':range(50, 55),                    # Create pandas DataFrame
                     'x2':['a', 'd', 'x', 'a', 'd'],
                     'x3':range(7, 2, - 1),
                     'x4':['x', 'y', 'y', 'z', 'y']})
print(data)                                                 # Print pandas DataFrame


table 1 DataFrame rename column pandas dataframe index python


Have a look at the previous table. It shows that our example pandas DataFrame comprises five rows and four columns.


Example: Change Column Name of pandas DataFrame by Index Using rename() Function

The following code explains how to rename a particular variable of a pandas DataFrame by index location in Python.

To achieve this, we can use the rename function as shown in the Python code below:

data_new = data.rename(columns = {data.columns[2]: 'new'})  # Apply rename function
print(data_new)                                             # Print updated DataFrame


table 2 DataFrame rename column pandas dataframe index python


By executing the previous code, we have created Table 2, i.e. a new pandas DataFrame where the third column name has been changed from “x3” to “new”.


Video & Further Resources

Have a look at the following video instruction on my YouTube channel. In the video, I illustrate the Python codes of this article.



Besides that, you might read some of the other Python tutorials on my homepage. You can find some interesting tutorials below:


In this article, I have explained how to modify the name of a pandas DataFrame column by index in Python programming. Don’t hesitate to let me know in the comments section below, if you have further comments or questions. Furthermore, don’t forget to subscribe to my email newsletter in order to receive updates on new tutorials.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.