Assign a Name to a Pandas Series Index

If you are familiar with what a series is, you can learn about different ways to assign a name to its index by going through the following methods. However, if you need to learn more about series and their creation, you can refer to the thread Building Pandas series with several datatypes.

1. Using "name" attribute of the index:

2. Using "rename_axis()" method:

The rename_axis() method is used to change the name of the axis labels of a Pandas DataFrame or Series. It is a flexible way of renaming the index or column labels of a Pandas object. The method can be applied to:

  • Row Index, which is specified using axis = 0 or axis = "index" argument.
  • Column Index, which is specified using axis = 1 or axis = "column" argument.

Row Index is the default value specified in this method and we don’t necessarily have to explicitly define it, so don’t get confused if the axis argument is missing in the sample code below.

Note: Specifying inplace = True ensures that the changes will be made to the original defined series and it’ll not create a new copy of it.

3. Using the "index" attribute and "rename()" method:

  • The rename() method is also another powerful and flexible way through which one can change the name of the index or the column labels.
  • The axis argument is not used in the sample code below, but the index attribute is. This is done because if axis is used, rename() attempts to rename each value in the index, which requires us to specify a collection of values rather than a single one.

Note: Specifying inplace = True ensures that the changes will be made to the original defined series and it’ll not create a new copy of it.

1 Like