【发布时间】: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