There are two approaches to rename index/columns in Pandas DataFrame:
(1) Set new index name by df.index.names
df.index.names = ['org_id']
(2) Rename index name with rename_axis
df.rename_axis('org_id')
(3) Rename column name with rename_axis
df.rename_axis('col_index', axis=1)
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 index/axis name in Pandas
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: Pandas rename index name - .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: Pandas rename index name -df.index.rename()
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 Pandax index level by 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')]
Step 6: Pandas rename index column
To rename column index in Pandas we need to pass parameter axis=1
to method rename_axis()
:
df.rename_axis('col_index', axis=1)