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

September 18, 2021    /    Viewed: 248    /    Comments: 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!