Examples of how to add a name or rename an axis of a dataframe with pandas:
Table of contents
Create a dataframe
Let's create a dataframe with pandas:
import pandas as pdimport numpy as npdata = np.random.randint(5, size=(3,3))df = pd.DataFrame(data=data,columns=['A','B','C'])print(df)
returns
A B C0 0 2 41 4 4 22 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 61 102 7dtype: 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 Ci0 0 2 41 4 4 22 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
i0 61 102 7dtype: int64
with the name of axis=0 => i.
