python - 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)
感谢任何帮助。
解决方案
使用.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
推荐阅读
- javascript - 函数 JavaScript 中的函数
- google-cloud-sdk - 带有 Python 的 Google Cloud Platform SDK
- c# - Aspose.zip 错误意外结束数据损坏错误
- hadoop - 将 Gogle colab 中的文件从文件夹移动到 hdfs
- swift - 如何将此处的 HTTP 请求的响应公开给其他函数?(迅速)
- python - 如何在特定频道 discord.py 下方创建频道
- angularjs - 运行此代码时出现断言错误:错误将是 - (AssertionError:预期假等于真)
- mongodb - Mongodb LOCAL 连接太慢(非常非常慢)
- html - 标签和 felder 不在行的中心
- drools - Drools 6.5:java.lang.RuntimeException:全局的非法类。预期 [com.user.PersonAccount],找到 [com.user.PersonAccount]