I have two dataframes as follows:
df1 = pd.DataFrame({"id":["01", "02", "03", "04", "05", "06"],
"string":["This is a cat",
"That is a dog",
"Those are birds",
"These are bats",
"I drink coffee",
"I bought tea"]})
df2 = pd.DataFrame({"category":[1, 1, 2, 2, 3, 3],
"keywords":["cat", "dog", "birds", "bats", "coffee", "tea"]})
My dataframes look like this
df1:
id string
01 This is a cat
02 That is a dog
03 Those are birds
04 These are bats
05 I drink coffee
06 I bought tea
df2:
category keywords
1 cat
1 dog
2 birds
2 bats
3 coffee
3 tea
I would like to have an output column on df1 which is the category if at least one keyword in df2 is detected in each string in df1, otherwise return None. The expected output should be the following.
id string category
01 This is a cat 1
02 That is a dog 1
03 Those are birds 2
04 These are bats 2
05 I drink coffee 3
06 I bought tea 3
I can think of looping over keywords one-by-one and scan through string one-by-one but it is not efficient enough if data is getting big. May I have your suggestions how to improve? Thank you.