Write a Python code to rename the given axis in a dataframe

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for renaming the axis is,

Rename index:
index    Id    Age    Mark
   0    1.0    12.0   80.0
   1    2.0    12.0   90.0
   2    3.0    14.0   NaN
   3    NaN    13.0   95.0
   4    5.0    NaN    85.0

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Apply df.rename_axis() function inside axis name as ‘index’ and set axis=1

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

Example

import pandas as pd
df = pd.DataFrame({"Id":[1, 2, 3, None, 5],
                     "Age":[12, 12, 14, 13, None],
                     "Mark":[80, 90, None, 95, 85],
                  })
print("Dataframe is:\n",df)
print("Rename index:")
df = df.rename_axis('index',axis=1)
print(df)

Output

Dataframe is:
   Id    Age    Mark
0 1.0    12.0   80.0
1 2.0    12.0   90.0
2 3.0    14.0   NaN
3 NaN    13.0   95.0
4 5.0    NaN    85.0
Rename index:
index    Id    Age    Mark
   0    1.0    12.0   80.0
   1    2.0    12.0   90.0
   2    3.0    14.0   NaN
   3    NaN    13.0   95.0
   4    5.0    NaN    85.0
raja
Published on 12-Feb-2021 10:27:00
Advertisements