w3resource

Pandas Series: str.join() function

Series-str.join() function

The str.join() function is used to Join lists contained as elements in the Series/Index with passed delimiter.

If the elements of a Series are lists themselves, join the content of these lists using the delimiter passed to the function. This function is an equivalent to str.join().

Syntax:

Series.str.join(self, sep)
Pandas Series: str.join() function

Parameters:

Name Description Type/Default Value Required / Optional
sep Delimiter to use between list entries. str Required

Returns: Series/Index: object
The list entries concatenated by intervening occurrences of the delimiter.

Raises: AttributeError
If the supplied Series contains neither strings nor lists.

Notes:If any of the list items is not a string object, the result of the join will be NaN

Example - Example with a list that contains non-string elements:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([['tiger', 'lion', 'deer'],
              [2.2, 3.3, 4.4],
              ['fox', np.nan, 'cat'],
              ['camel', 5.5, 'monkey'],
              ['duck', ['swan', 'fish'], 'guppy']])
s

Output:

0            [tiger, lion, deer]
1                [2.2, 3.3, 4.4]
2                [fox, nan, cat]
3           [camel, 5.5, monkey]
4    [duck, [swan, fish], guppy]
dtype: object

Example - Join all lists using a ‘-‘. The lists containing object(s) of types other than str will produce a NaN:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([['tiger', 'lion', 'deer'],
              [2.2, 3.3, 4.4],
              ['fox', np.nan, 'cat'],
              ['camel', 5.5, 'monkey'],
              ['duck', ['swan', 'fish'], 'guppy']])
s.str.join('-')

Output:

0    tiger-lion-deer
1                NaN
2                NaN
3                NaN
4                NaN
dtype: object

Previous: Series-str.get() function
Next: Series-str.len() function



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-str-join.php