join or concatenate string in pandas python – Join() function is used to join or concatenate two or more strings in pandas python with the specified separator. In this tutorial lets see
- How to join or concatenate two strings with specified separator
- how to concatenate or join the two string columns of dataframe in python.
- How to concatenate or join an integer and string column in python
Syntax for string join() function in python:
str.join(sequence)
sequence — This is a sequence of the elements to be joined.
Example 1 – join or concatenate two strings
Simple string join is shown below
a= "python is" b="My Favourite Language" #join with space separator print " ".join((a,b)) #join with : separator print ": ".join((a,b))
so the output will be
python is My Favourite Languagepython is: My Favourite Language
Example 2 – concatenate or join an integer and string column in python:
Create dataframe:
##create dataframe import pandas as pd d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'], 'Revenue':[23400344.567,54363744.678,56789117.456,4132454.987]} df=pd.DataFrame(d) print df
the dataframe will be
Join or concatenate columns of dataframe in python:
# join or concatenate two columns in pythons with space as separator df['Quarters_revenue_concat1'] = df["Quarters"]+ " " + df["Revenue"].map(str) print df
- Revenue column is type casted to string before concatenating
resultant dataframe will have space separated concatenated column
# join or concatenate two columns in pythons with dash as separator df['Quarters_revenue_concat1'] = df["Quarters"]+ "-" + df["Revenue"].map(str) print df
resultant dataframe will have dash separated concatenated column
Example 3 on concatenation or join of two string columns in python dataframe:
Create dataframe:
##create dataframe import pandas as pd d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'], 'Alias' : ['q1','q2','q3','q4']} df=pd.DataFrame(d) print df
dataframe will be
# join or concatenate two string columns in python with apply function df[' Quarters_Alias_concat'] = df[['Quarters', 'Alias']].apply(lambda x: '-'.join(x), axis=1) print df
We will be using apply function to join two string columns of the dataframe so the resultant dataframe will be