w3resource

Pandas Series: add_prefix() function

Prefix labels with string prefix in Pandas series

The add_prefix() function is used to prefix labels with string prefix.

For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed.

Syntax:

Series.add_prefix(self, prefix)
Pandas Series add_prefix image

Parameters:

Name Description Type/Default Value Required / Optional
prefix The string to add before each label. str Required

Returns: Series or DataFrame
New Series or DataFrame with updated labels.

Example:

Python-Pandas Code:

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

Output:

0    2
1    3
2    4
3    5
dtype: int64
Pandas Series add_prefix image

Python-Pandas Code:

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

Output:

item_0    2
item_1    3
item_2    4
item_3    5
dtype: int64

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({'X': [2, 3, 4, 5],  'Y': [4, 5, 6, 7]})
df

Output:

  X	Y
0	2	4
1	3	5
2	4	6
3	5	7

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({'X': [2, 3, 4, 5],  'Y': [4, 5, 6, 7]})
df.add_prefix('col_')

Output:

  col_X	col_Y
0	 2	    4
1	 3	    5
2	 4	    6
3	 5	    7

Previous: Replace values in Pandas Series
Next: Suffix labels with string suffix in Pandas series



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://www.w3resource.com/pandas/series/series-add_prefix.php