Concatenate two text columns into one column in Pandas

Python Methods and Functions

Method # 1: Using the cat () function
We can also use different delimiters when connecting. eg -, _, ”” etc.

# pandas import

import pandas as pd

  

df = pd.DataFrame ({ 'Last' : [ ' Gaitonde' , 'Singh' , ' Mathur' ],

'First' : [ 'Ganesh' , ' Sartaj' , 'Anjali' ]})

  

print ( ' Before Join' )

print (df, '' )

  

print ( 'After join' )

df [ 'Name' ] = df [ 'First' ]. str . Cat (df [ 'Last' ], sep = " " )

print (df)

Output:

Method # 2: Using a lambda function

This method generalizes an arbitrary number of string columns, replacing df [[& # 39; First & # 39 ;, & # 39; Last & # 39;]] with any portion of your data frame column, for example df.iloc [:, 0: 2] .apply (lambda x: & # 39; & # 39; .join (x), axis = 1).

# pandas import

import pandas as pd

 

df = pd.DataFrame ({ ' Last' : [ 'Gaitonde' , 'Singh' , ' Mathur' ],

  ' First' : [ ' Ganesh' , 'Sartaj' , 'Anjali' ]})

  

print ( ' Before Join' )

print (df, '' )

  

print ( 'After join' )

df [ 'Name' ] = df [[ ' First' , 'Last' ]]. apply ( lambda x : '' . join (x), axis = 1 )

print (df)

Output:

Method # 3 : Using the + operator

We need to convert the dataframe elements to a string before concatenating. We can also use different delimiters during the concatenation, for example -, _, & # 39; & # 39; etc.

# pandas import

import pandas as pd

 

df = pd.DataFrame ({ 'Last' : [ 'Gaitonde' , 'Singh' , ' Mathur' ],

'First' : [ 'Ganesh' , ' Sartaj' , 'Anjali' ]})

  

print ( ' Before Join' )

print (df, '' )

  

print ( 'After join' )

df [ 'Name' ] = df [ "First" ]. astype ( str ) + "" + df [ "Last" ]

print (df)

Output:





Get Solution for free from DataCamp guru