代码之家  ›  专栏  ›  技术社区  ›  oymonk

如何从pandas中的字符串中提取带有变量的正则表达式?

  •  2
  • oymonk  · 技术社区  · 10 月前

    我有一个包含文本的数据框列,我想创建一个新列,其中包含有名称的句子,但不包含其他句子。希望最终的结果是这样的:

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

    我能够从名字列表中识别出包含名字的单元格,但我在提取包含名字的句子的部分遇到了问题。

    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)
    

    当我打印数据帧时,每一行都有一个名称 df[col_3'] 生成一个空列表。

    任何帮助感谢。

    2 回复  |  直到 10 月前
        1
  •  1
  •   Panda Kim    10 月前

    代码

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

    df:

    enter image description here

        2
  •  1
  •   Sheldon    10 月前

    如果你不想使用正则表达式,你可以修改这里提供的答案 SO post 自动识别包含中指定名称之一的句子 last_names_list :

    last_names_list = ['May','Brian']
    pattern = '|'.join(last_names_list)
    df[df.ColumnA.str.contains(pattern)]
    

    这将返回:

    ColumnA
    1   Lorum Ipsum. Send the contract to May. Lorum I...
    2   Junk Mail from Brian.