首页 > 解决方案 > re.search if else 语句和replace()

问题描述

我对编程很陌生。我正在尝试使用 re.search 和 replace 函数创建一个 if elif 语句,但没有得到我想要的 else 语句的结果。所以这就是我想要做的:

if re.search('.*[Cc]orona.*|.*[Qq]uarantine.*', str(table['reason'])):
    table['new_reason'] = table['reason'].replace('.*[Cc]orona.*|.*[Qq]uarantine.*', 'covid related', regex = True)
elif re.search('.*', (str(table['reason'])):
    table['new_reason'].replace('.*', 'other reason', regex = True)' 

换句话说,我正在尝试创建一个新列,如果“原因”列包含“电晕”或“隔离”一词,则该值将与“covid 相关”。如果不是,我希望它返回“其他原因”。现在,它只适用于 if 语句(即,将其中带有“corona”和“quarantine”的值转换为“covid related”)。我不会将所有其他值转换为“其他原因”。

我也试过这个,但得到相同的结果:

if re.search('.*[Cc]orona.*|.*[Qq]uarantine.*', str(table['reason'])):
    table['new_reason'] = table['reason'].replace('.*[Cc]orona.*|.*[Qq]uarantine.*', 'covid related', regex = True)
else:
    table['new_reason'].replace('.*', 'other reason', regex = True)

感谢任何帮助。

标签: pythonregexpandasif-statementreplace

解决方案


使用.str.contains('quarantine|corona', case=False)(或,匹配整个单词,r'\b(?:quarantine|corona)\b')条件与np.where

import pandas as pd
import numpy as np
df = pd.DataFrame({'reason':['__ Corona ___', '++++ quarantine +++', '__ CORONA ___', '++++ QUARANTINE +++', '--- NA ---']})
df['new_reason'] = np.where(df['reason'].str.contains('quarantine|corona', case=False), 'covid related', 'other reason')
>>> df
                reason     new_reason
0        __ Corona ___  covid related
1  ++++ quarantine +++  covid related
2        __ CORONA ___  covid related
3  ++++ QUARANTINE +++  covid related
4           --- NA ---   other reason

推荐阅读