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

Python : how to extract the first substring of a string with separator into another column?

I have a dataframe with a column "CCR" whose values are as such :
"Aaaa;Bbbb;Cccc", or "Bbbb;;Cccc", or "Cccc;Bbbb;Aaaa".
I would like to take only the first part (before the ";") and put this into another column "1st CCR". I can’t seem to make it work using the split function. With this code I tried, nothing happens.
Can you help ?

def get_1stCCR(row):
  for row in df['CCR']:
    df['1stCCR'] = row.split(";")[0]

df['CCR'].apply(get_1stCCR)

>Solution :

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

You can do the following using a lambda function:

df['newCCR']=df['CCR'].apply(lambda x:x[0:x.index(';')])

If some rows don’t have ‘;’ in them, you should use:

df['newCCR']=df['CCR'].apply(lambda x:x[0:x.index(';') if ';' in x else None])
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