Signup/Sign In
PUBLISHED ON: MARCH 31, 2021

Pandas Series add_prefix() Method

If we want to alter the index names of the Series we can alter them by adding the prefix to the Series index using the Series.add_prefix() method. This method adds a string label at the beginning of each index or row and returns a Series with the updated labels.

The below is the syntax of the Series.add_prefix() method.

Syntax

Series.add_prefix(prefix)

Parameters

prefix: This represents the str that is the string to be added before each label.

Example: Prefix labels of Series in Pandas

Let's create a Series and add the string label at the beginning of the row of the Series using the Series.add_prefix() method. See the below example.

The Series.add_prefix() method prefixes the string 'index_' to the rows of the Series.

#importing pandas as pd
import pandas as pd
#creating Series
s= pd.Series([1,2,3])
print("---------The series is------")
print(s)
print("-------After updating, the new series is---------")
print(s.add_prefix('index_'))


---------The series is------
0 1
1 2
2 3
dtype: int64
-------After updating, the new series is---------
index_0 1
index_1 2
index_2 3
dtype: int64

Example 2: Prefix row labels of Series in Pandas

This example is similar to the previous one. Let's create a Series and add the string label at the beginning of the row of the Series using the Series.add_prefix() method. See the below example.

The Series.add_prefix() method prefixes the string 'Student_' to the rows of the Series.

#importing pandas as pd
import pandas as pd
#creating Series
s= pd.Series(['Navya','Vindya','Sinchana'],index=[1,2,3])
print("---------The series is------")
print(s)
print("-------After updating, the new series is---------")
print(s.add_prefix('Student_'))


---------The series is------
1 Navya
2 vindya
3 sinchana
dtype: object
-------After updating, the new series is---------
Student_1 Navya
Student_2 Vindya
Student_3 Sinchana
dtype: object

Conclusion

In this tutorial, we learned the Python pandas Series.add_prefix() method. We learned syntax and solved examples by applying this method to series.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.