w3resource

Pandas Series: rename() function

Alter Series index in Pandas

The rename() function is used to alter Series index labels or name.

Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.

Alternatively, change Series.name with a scalar value.

Syntax:

Series.rename(self, index=None, **kwargs)
Pandas Series rename image

Parameters:

Name Description Type/Default Value Required / Optional
index dict-like or functions are transformations to apply to the index. Scalar or hashable sequence-like will alter the Series.name attribute. scalar, hashable sequence, dict-like or function optional
copy Whether to copy underlying data. bool
Default Value: True
Required
inplace Whether to return a new Series. If True then value of copy is ignored. bool
Default Value: False
Required
level In case of a MultiIndex, only rename labels in the specified level. int or level name
Default Value: None
Required

Returns: Series
Series with index labels or name altered.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s

Output:

0    2
1    3
2    4
dtype: int64
Pandas Series rename image

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s.rename("my_name")  # scalar, changes Series.name

Output:

0    2
1    3
2    4
Name: my_name, dtype: int64

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s.rename(lambda x: x ** 2)  # function, changes labels

Output:

0    2
1    3
4    4
dtype: int64

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s.rename({1: 4, 2: 5})  # mapping, changes labels

Output:

0    2
4    3
5    4
dtype: int64

Previous: Object with matching indices as other object in Pandas
Next: Set the name of the axis in Pandas



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/pandas/series/series-rename.php