Concatenate strings with different options .
Returns str, Series or Index
Options
Without using any separator sep = None ( default )
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex']}
df = pd.DataFrame(data=my_dict)
print(df.NAME.str.cat())
Output ( without any separator all are joined )
RaviRajuAlex
Let us try with separator
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex']}
df = pd.DataFrame(data=my_dict)
print(df.NAME.str.cat(sep=' '))
Output
Ravi Raju Alex
We can use , as separator.
print(df.NAME.str.cat(sep=','))
Output
Ravi,Raju,Alex
Using domain name and userid
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex'],
'DOMAIN':['example.com','example.net','example.org'] }
df = pd.DataFrame(data=my_dict)
print(df.NAME.str.cat(df['DOMAIN'],sep='@'))
Output
0 Ravi@example.com
1 Raju@example.net
2 Alex@example.org
Handling missing data
By using option na_rep='#' we will say how to handle missing data.
import pandas as pd
import numpy as np
my_dict={'NAME':['Ravi','Raju','Alex',np.nan],
'DOMAIN':['example.com','example.net','example.org','example.co']}
df = pd.DataFrame(data=my_dict)
print(df.NAME.str.cat(df['DOMAIN'],sep='@',na_rep='#'))
Output
0 Ravi@example.com
1 Raju@example.net
2 Alex@example.org
3 #@example.co
« Pandas
contains() Converting char case slice()
split()
← Subscribe to our YouTube Channel here