There are two approaches to rename index in Pandas DataFrame:

(1) Set new name by df.index.names

df.index.names = ['org_id']

(2) Rename index name with rename_axis

df.rename_axis('org_id')

In the rest of this article you can find a few practical examples on index renaming for columns and rows.

To start, let's create a sample DataFrame with 2 columns:

import pandas as pd
df = pd.DataFrame({
    'name':['Softhints', 'DataScientyst'],
    'url':['https://www.softhints.com', 'https://datascientyst.com']
})
name url
0 Softhints https://www.softhints.com
1 DataScientyst https://datascientyst.com

Step 1: Check for name in DataFrame index/axis

First let's check if there's an index name by:

df.index

The index don't have any name set:

RangeIndex(start=0, stop=2, step=1)

The same is for the columns:

df.columns

no name on column axis:

Index(['name', 'url'], dtype='object')

Step 2: Rename Pandas index by .rename_axis()

Pandas offers a method called .rename_axis('companies') which is intended for index renaming.

To rename index with rename_axis in Pandas DataFrame use:

df.rename_axis('org_id')

this will result into:

name url
org_id
0 Softhints https://www.softhints.com
1 DataScientyst https://datascientyst.com

You can notice the index name org_id which is on the top of the index.

Let's check the index name by df.index:

RangeIndex(start=0, stop=2, step=1, name='org_id')

It's visible by name='org_id'

For changing column index name you can use - axis=1:

df = df.rename_axis('company_data', axis=1)

result:

company_data name url
org_id
0 Softhints https://www.softhints.com
1 DataScientyst https://datascientyst.com

and for columns we have name added to the index:

Index(['name', 'url'], dtype='object', name='company_data')

Step 3: Rename Pandas index with df.index.names

Another option to rename any axis is to use the names attribute: df.index.names.

So to rename the index name is by:

df.index.names = ['org_id']

For columns we can use:

df.columns.names = ['company_data']

The result is exactly the same as in the previous step.

Step 4: Rename Pandas index with method df.index.rename('test')

Pandas offers method index.rename which can be used to change the index name for both rows and/or columns:

df.index = df.index.rename('test')

result:

RangeIndex(start=0, stop=2, step=1, name='test')

Step 5: Get index in DataFrame by its name

Finally let's cover how index can be extracted by it's name:

df.index.get_level_values('test')

This is useful for hierarchical indexes.

So to access data by index name use:

df.loc[df.index.get_level_values('test')]

Resources