Sunday 10 September 2023

Joining Elements of a Pandas Series with a Delimiter

Using String join() method, we can join the elements of a series using given delimeter.

 

Example

series = pd.Series(['India', 'China', 'Bangladesh', 'Sri Lanka'], index = ['A', 'B', 'C', 'D'])
join_by_comma = ', '.join(series)

 

In the above example, I defined a Pandas Series called ‘series’ with values ['India', 'China', 'Bangladesh', 'Sri Lanka']. Using the statement

', '.join(series) method on the series object, we join the elements of the Series into a single string using the specified delimiter ', '.

 

join_series_elements.py
import pandas as pd

series = pd.Series(['India', 'China', 'Bangladesh', 'Sri Lanka'], index = ['A', 'B', 'C', 'D'])
join_by_comma = ', '.join(series)
join_by_colon = ': '.join(series)

print('join_by_comma : ', join_by_comma)
print('\njoin_by_colon : ', join_by_colon)

 

Output

join_by_comma :  India, China, Bangladesh, Sri Lanka

join_by_colon :  India: China: Bangladesh: Sri Lanka

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment