Replace the value on a column based on the match, obtained using regex, on another column (Python Pandas)

Viewed 52

I have a pandas data frame like this:

       AGENCY| CLIENT
     ___________________________
     AAA     | CLIENT_ONE
     AAB     | CLIENT_TWO SOMETHING
     AAF     | CLIENT_TWO SOMETHING and 55
     KAK     | CLIENT THREE

If the column CLIENT contains the string 'CLIENT_TWO' (followed by something or not), I want to replace the value of the corresponding column AGENCY with the string 'HELLO'. The final result should look like this:

       AGENCY| CLIENT
     ___________________________
     AAA     | CLIENT_ONE
     HELLO   | CLIENT_TWO SOMETHING
     HELLO   | CLIENT_TWO SOMETHING else 55
     KAK     | CLIENT THREE

How can I do it using regex?

1 Answers

You can use str.contains and loc:

df.loc[df['CLIENT'].str.contains('CLIENT_TWO'), 'AGENCY'] = 'HELLO'
Related