【问题标题】:Make it faster to check if a certain regex is present in the text加快检查文本中是否存在某个正则表达式
【发布时间】:2022-07-06 15:03:32
【问题描述】:

我有问题。我想检查某个正则表达式是否出现在文本中(这个正则表达式稍后会变得更复杂。)。不幸的是,我的代码 sn-p 运行,但需要很长时间。如何重写代码以使其更快、更高效?

如果文本中存在该元素,则应找到相应元素的代码编号并将其写入新列。如果不存在,则应写入999

数据框

   customerId                text element  code
0           1  Something with Cat     cat     0
1           3  That is a huge dog     dog     1
2           3         Hello agian   mouse     2

代码sn-p

import pandas as pd
import copy
import re
d = {
    "customerId": [1, 3, 3],
    "text": ["Something with Cat", "That is a huge dog", "Hello agian"],
     "element": ['cat', 'dog', 'mouse']
}
df = pd.DataFrame(data=d)
df['code'] = df['element'].astype('category').cat.codes
print(df)

def f(x):
    match = 999
    for element in df['element'].unique():
        check = bool(re.search(element, x['text'], re.IGNORECASE))
        if(check):
            #print(forwarder)
            match = df['code'].loc[df['element']== element].iloc[0]
            break
    x['test'] = match
    return x
    #print(match)
df['test'] = None
df = df.apply(lambda x: f(x), axis = 1)

预期输出

   customerId                text element  code  test
0           1  Something with Cat     cat     0     0
1           3  That is a huge dog     dog     1     1
2           3         Hello agian   mouse     2   999

【问题讨论】:

  • 所以你想要的只是,如果元素出现在文本 test=code 中,如果不是 text=999,对吧?
  • 是的,你是对的。

标签: python pandas dataframe


【解决方案1】:

您可以使用pandas.str.contains,然后使用numpy.where 填充df['code']999

import numpy as np

mask = df['text'].str.contains('|'.join(df['element']), case=False)
df['test'] = np.where(mask, df['code'], 999)
print(df)

输出:

   customerId                text element  code  test
0           1  Something with Cat     cat     0     0
1           3  That is a huge dog     dog     1     1
2           3         Hello agian   mouse     2   999

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 2014-07-13
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2013-04-29
    • 2016-12-20
    • 1970-01-01
    • 2018-12-12
    相关资源
    最近更新 更多