【问题标题】:re.search if else statement and replace()re.search if else 语句和replace()
【发布时间】:2021-01-25 08:48:01
【问题描述】:

我对编程很陌生。我正在尝试使用 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)

感谢任何帮助。

【问题讨论】:

  • 我觉得你的逻辑应该是np.where(table["reason"].str.contains('.*[Cc]orona.*|.*[Qq]uarantine.*'), "covid related", "other reasons")
  • 但没有得到我想要的结果如果你描述你得到的结果,以及它与你想要的结果有何不同,这会有所帮助。
  • @HenryYik,谢谢你。那行得通。出于兴趣..你知道如何使用 if else 语句吗?
  • @JohnGordon,我现在试着具体说明一下,谢谢。

标签: python regex pandas if-statement replace


【解决方案1】:

使用.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2014-02-15
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多