apply lambda: delete the corresponding characters of A according to the multiple keywords of B

Viewed 36

How to delete the corresponding character in another column based on the value of a column?

import pandas as pd

df = pd.DataFrame([['ABCD','B'],['ABFJS','A,J'],['DGQEX','']],
                   index = [1,2,3],columns=['A','B'])

Example: I want to delete "ABCD" in the first row according to "B" and keep "ACD". Similarly, I want to delete "A" and "J" in the second row of 'ABFJS' according to 'A,J' and keep "BFS". The third line is unchanged. How can I do this? I have tried this, but it doesn't work

df.apply(    lambda x: [   x["A"].replace(i, "")  for i in str(x["B"]).split(",") ], axis=1)

returned in the second line is [BFJS, ABFS] instead of [BFS]

1 Answers

You can use regex' re.sub() function like so:

df.apply(lambda x: re.sub("|".join(x['B'].split(',')), "", x["A"]), axis=1)

Print out:

1      ACD
2      BFS
3    DGQEX
Related