re.search if else statement and replace()

Viewed 175

I'm quite new to programming. I'm trying to create an if elif statement with re.search and the replace function, but don't get the result I want for the else statement. So this is what I want to do:

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)' 

In other words, I'm trying to create a new column where the value would be "covid related" if the 'reason' column contains the word corona or quarantine. If not, I want it to return "other reason". Now, it only works with the if statement (i.e. transforms the values with 'corona' and 'quarantine' in them to 'covid related'). I does not transform all the other values to 'other reason'.

I also tried this, but get the same result:

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)

Appreciate any help.

1 Answers

Use .str.contains('quarantine|corona', case=False) (or, to match whole words, r'\b(?:quarantine|corona)\b') condition with 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
Related