Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
                          
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading