How to prefix string to a pandas series labels?

PandasServer Side ProgrammingProgramming

In pandas Series functionalities we have a function called add_prefix that is used to add a string prefix to the labels. Particularly in pandas series the row labels will be prefixed with string.

The add_prefix method will return a new series object with prefixed labels. It will add the given string before the row labels of the series.

Example

import pandas as pd

series = pd.Series(range(1,10,2))
print(series)

# add Index_ prefix to the series labels
result = series.add_prefix('Index_')

print("Prefixed Series object with a string: ", result)

Explanation

In this following example, we have created a pandas series using python range function and the index labels for this series object are auto created values between 0 to 4. And those index values are updated with the string prefix ‘Index_’ by using add_prefix method.

Output

0   1
1   3
2   5
3   7
4   9
dtype: int64

Prefixed Series object with a string:
Index_0   1
Index_1   3
Index_2   5
Index_3   7
Index_4   9
dtype: int64

This block of output is displaying both the series objects, top one is initial series without string prixif and another one is a series with updated index label by string prefix.

Example

import pandas as pd

sr = pd.Series({'a':1,'b':2,'c':3})

print(sr)

# add prefix
result = sr.add_prefix('Lable_')

print(result)

Explanation

Here is another example for the pandas series.add_prefix method, the initial series object is created by a python dictionary with named labels (a, b, c).

Output

a   1
b   2
c   3
dtype: int64

Lable_a   1
Lable_b   2
Lable_c   3
dtype: int64

We updated the named index labels by adding a string ‘Lable_’ before the original index labels. The resultant series object can be seen in the above output block.

raja
Published on 17-Nov-2021 08:32:22
Advertisements