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

Concatenating strings in a apandas dataframe

below is an example of string that is a variable of my df:

df_final['newa_1'][8395389]
"['Y02T  10/70' 'Y02E  60/00' 'Y02T  90/16' 'Y04S  10/126' 'Y02T  10/7072' 'Y02T  90/12' 'Y02T   90/14']"

What I would like o do is to put a "_" within the elements between ” regardless of how many spaces there are. So, in the example above, the output should be something like:

"['Y02T_10/70' 'Y02E_60/00' 'Y02T_90/16' 'Y04S_10/126' 'Y02T_10/7072' 'Y02T_90/12' 'Y02T_90/14']"

Thank you

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

>Solution :

You can do it using re as follows:

foo = "['Y02T  10/70' 'Y02E  60/00' 'Y02T  90/16' 'Y04S  10/126' 'Y02T  10/7072' 'Y02T  90/12' 'Y02T   90/14']"

import re

re_whitespace = re.compile(r"\s+")

re_whitespace.sub('_', foo).replace("'_'", "' '")

Giving you:

"['Y02T_10/70' 'Y02E_60/00' 'Y02T_90/16' 'Y04S_10/126' 'Y02T_10/7072' 'Y02T_90/12' 'Y02T_90/14']"

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