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

How to extract a specific part of string in a column and assign it to a new column in pandas?

I want to extract a specific part of column in pandas and assign it to a new column. The part that I want to extract is not fixed in a string for eg;
MC-ABC 2+0/XPIC 2+0 or MisMatch!MC-ABS 2+0 ::: / XPIC 2+0.
Here I want to extract only XPIC.

I tried using regular expression but could not get the desired result.

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 use str.extract()

import pandas as pd

# Create a sample DataFrame
data = {'column': ['MC-ABC 2+0/XPIC 2+0', 'MisMatch!MC-ABS 2+0 ::: / XPIC 2+0']}
df = pd.DataFrame(data)

# Extract the desired part using regular expression and assign it to a new column
df['new_column'] = df['column'].str.extract(r'(\bXPIC\b)')

# Print the DataFrame
print(df)
        column                           new_column
0  MC-ABC 2+0/XPIC 2+0                      XPIC
1  MisMatch!MC-ABS 2+0 ::: / XPIC 2+0       XPIC
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