Search code examples
pythonpandasregexvariables

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.

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