I'm having a problem concatenating two columns

When I’m concatenating two columns of type String in my DataFrame it’s giving me an error.

I’m taking the spaces out of it, is this way I’m doing it right?

My code, concat columns:

df_control['NAME'] = df_control['NAME'].astype(str)
df_control['LASTNAME'] = df_control['LASTNAME'].astype(str)
df_control['LASTNAME'] = df_control['LASTNAME'].str.split()
df_control['NAME'] = df_control['NAME'].str.split()

df_control['FULL NAME'] = df_control['NAME']+' '+df_control['LASTNAME']


Example:

0 NAME LASTNAME
1 Wilson  Nunes

Error:

TypeError: can only concatenate list (not "str") to list

Expected:

0 NAME LASTNAME  FULL NAME
1 Wilson  Nunes   Wilson  Nunes

>Solution :

It is because str.split will return a list which you cannot concatenate with ' '. It suffices to call columns:

df_control['FULL NAME'] = df_control['NAME'].astype(str) + ' ' + \
                          df_control['LASTNAME'].astype(str)

You don’t even need astype(str) if the values in those columns were already strings:

df_control['NAME']+ ' '+ df_control['LASTNAME']
                          

Leave a Reply