How to add a name or rename an axis of a dataframe with pandas ?

Published: September 18, 2021

Tags: Python; Pandas; DataFrame;

DMCA.com Protection Status

Examples of how to add a name or rename an axis of a dataframe with pandas:

Create a dataframe

Let's create a dataframe with pandas:

import pandas as pd
import numpy as np

data = np.random.randint(5, size=(3,3))

df = pd.DataFrame(data=data,columns=['A','B','C'])

print(df)

returns

   A  B  C
0  0  2  4
1  4  4  2
2  1  2  4

Note: to get info about the dataframe axis, a solution is to use pandas.DataFrame.axes

print(df.axes)

returns here

[RangeIndex(start=0, stop=3, step=1), Index(['A', 'B', 'C'], dtype='object')]

Note also that a function such as sum():

df.sum(axis=1)

returns

0     6
1    10
2     7
dtype: int64

with no axis name

Add an axis name (or rename it)

To sdd an axis name to a dataframe a solution is to use rename_axis:

df.rename_axis("i", axis="rows", inplace=True)

    df.rename_axis("j", axis="columns", inplace=True)

Then df will returns:

j  A  B  C
i         
0  0  2  4
1  4  4  2
2  1  2  4

and

df.axes

gives now

[RangeIndex(start=0, stop=3, step=1, name='i'), Index(['A', 'B', 'C'], dtype='object', name='j')]

and

df.sum(axis=1)

gives

i
0     6
1    10
2     7
dtype: int64

with the name of axis=0 => i.

References