coelidonum
coelidonum

Reputation: 543

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

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?

Upvotes: 2

Views: 286

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

You can use str.contains and loc:

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

Upvotes: 3

Related Questions