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

Extract values from string column in pandas dataframe

I have a column in a dataframe which have a pattern as shown in the below example

id=1;name=x;color=blue;

I am trying to extract the value for name and store it in the same dataframe with column name as "name" and value is "x"

I tried the below code but it doesn’t seem to work correctly

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['name'] = df['col'].str.extract("'name': '(.*?)'")

>Solution :

The 'name': '(.*?)' regex is meant to extract a string between 'name': ' and the next ' char. You do not have single quotes, nor : in your input.

You can use

df['name'] = df['col'].str.extract(r"name=([^;]*)")

See the regex demo, name=([^;]*) matches the name= as left-hand side context and extracts one or more chars other than a ; right after that into the name column.

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