I'm having a problem concatenating two columns

Question:

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

Asked By: Zan

||

Answers:

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']
                          
Answered By: Nuri Taş

all you need is this:

df_control['FULL NAME'] = df_control['NAME'].str.cat(df_control['LASTNAME'],' ')
Answered By: SergFSM
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.