Home > front end >  I'm having a problem concatenating two columns
I'm having a problem concatenating two columns

Time:09-09

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

CodePudding user response:

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']
                          

CodePudding user response:

all you need is this:

df_control['FULL NAME'] = df_control['NAME'].str.cat(df_control['LASTNAME'],' ')
  • Related