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 extract regex with variable from string in pandas?

I have a dataframe column containing text, and I’d like to make a new column which contains the sentences with names, but no other sentences. Hoping for an end result that looks like this:

spreadsheet printout with sentence in column A, and sentence with names in column 3

I am able to identify cells containing names from the list of names, but I’m stumbling on the part that extracts the sentence containing the name.

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

import re
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'ColumnA': ['Lorum ipsum. This is approved. Lorum Ipsum.', 'Lorum Ipsum. Send the contract to May. Lorum Ipsum.', 'Junk Mail from Brian.']
})


last_names_list = ['May','Brian']

df['last_names'] = ''
for x in last_names_list:
    df['last_names'] = np.where(df['ColumnA'].str.contains(x),x,df['last_names'])

def f(x,y):
    return re.findall(fr'[^.]{x}[^.]',y)

df['col_3'] = df.apply(lambda x: f(x['last_names'],x['ColumnA']), axis=1)

print(df)

When I print the dataframe, every row with a name in df[col_3'] produces an empty list.

Any help appreciated.

>Solution :

Code

pat = '|'.join(last_names_list)
df['col_3'] = df['ColumnA'].str.extract(rf'([^.]*?\b(?:{pat})\b.*?\.)')

df:

enter image description here

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