How to add underscore between "non" or "no" and the word followed by it using python?

Viewed 41

I wonder how to add underscore between "non" or "no" and the word followed by it using python. Thank you in advanced. For example,

Input dataframe:

enter image description here

Expected output dataframe:

enter image description here

1 Answers

You could use the pandas "apply" method as follows.

import pandas as pd

def func(s):
    tokens = s.split()
    i = 0
    while i<len(tokens):
        if tokens[i] in ["no","non"] and i < len(tokens)-1:
            tokens[i] = f"{tokens[i]}_{tokens[i+1]}"
            tokens.pop(i+1)
        i+=1
    return ' '.join(tokens)
            

df = pd.DataFrame({'id':[1,2], "text":["no damage car", "non damage car"]})
df["text"] = df["text"].apply(func)

The resulting dataframe df:

   id            text
0   1   no_damage car
1   2  non_damage car

Granted, the function being applied could be made "nicer" with the help of regular expressions.

Related