基于正则表达式匹配替换数据帧中的字符串值

2024-10-03 11:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个叫做python框架的列 此栏应有认证数据:“10/10/2011” 或者说:“未经认可” 但在大多数未经认证的情况下,该专栏都会有一些文本,例如: “这家企业没有经过认证……” 我想替换全文,只写:“未经认证”

现在,我写了一个函数:

def notAcredited(string):
    if ('Not' in string or 'not' in string):
        return  'Not Accredited'

我用一个循环来实现这个函数,可以用“.apply”方法来实现吗?在

^{pr2}$

Tags: or数据函数in文本框架stringif
1条回答
网友
1楼 · 发布于 2024-10-03 11:22:47

可以使用矢量化字符串方法^{}

In [72]: df = pd.DataFrame({'accredited': ['10/10/2011', 'is not accredited']})

In [73]: df
Out[73]: 
          accredited
0         10/10/2011
1  is not accredited

In [74]: df['accredited'] = df['accredited'].str.replace(r'(?i).*not.*', 'not accredited')

In [75]: df
Out[75]: 
       accredited
0      10/10/2011
1  not accredited

传递给replace的第一个参数,例如r'(?i).*not.*',可以是任何regex pattern。第二个可以是任何regex替换值,与^{}接受的类型相同。regex模式中的(?i)使模式不区分大小写,因此notNotNOtNoT等都匹配。在

Series.str.replace将对re.sub的调用循环化(这使得它比使用apply实现的更快,因为apply使用Python循环。)

相关问题 更多 >