How to replace part of string with pattern(regex) throw rows in dataframe

Viewed 47

My output: df with column final result

         final result
13649   |ReviewNG-ICV|Other
13650   |Other|ReviewNG-AO
13652   |Other|ReviewNG-AO|ReviewNG-CL
0       |Other
1       |Other
2       |Other

I want replace(or remove part of string) where specific "|Other" combine with other "tags", but it will still remain if it alone in cell So required output:

         final result
13649   |ReviewNG-ICV
13650   |ReviewNG-AO
13652   |ReviewNG-AO|ReviewNG-CL
0       |Other
1       |Other
2       |Other

I trying this code without any success:

df['final result']=df['final result'].apply(lambda x: x['final result'] if x['final result']!='|Other' else 'x') 
4 Answers

You can use

>>> df['final result'].str.replace(r'{0}(?!$)|(?!^){0}'.format(r'\|Other\b'), '', regex=True)
0               |ReviewNG-ICV
1                |ReviewNG-AO
2    |ReviewNG-AO|ReviewNG-CL
3                      |Other
Name: final result, dtype: object

See the regex demo. Details:

  • \|Other\b(?!$) - |Other as a whole word not at the end of string
  • | - or
  • (?!^)\|Other\b - |Other as a whole word not at the start of string.

My preferred solution would be something like

def f(row):
    content = row['final result']
    if content != '|Other'\
    and content.startswith('|Other'):
        return content[6:] #throw away '|Other' 
    else:
        return content
    

df['final result'] = df.apply(f, axis=1)

It doesn't use regex since I think it is an overshoot for such a simple parsing. The function is easy to read and understand, it takes the entire row as input so you can apply it to the df directly using the axis=1 argument.

If it is only equal to '|Other', then the simple way to write it is:

df.loc[df['final result'] == '|Other', 'final result'] = 'x'

You can use list comprehension:

df['final result'] = [x.replace('|Other', '') if x != '|Other' else x for x in df['final result']]

Output:

         final result
13649   |ReviewNG-ICV
13650   |ReviewNG-AO
13652   |ReviewNG-AO|ReviewNG-CL
0       |Other
1       |Other
2       |Other
Related