Input:
import pandas as pd
df_input = pd.DataFrame({'Keyword': {0: 'apple banana, orange',
1: 'apple orange ?banana "',
2: 'potato, piercing pot hole',
3: 'armor hard known'},
'Returns': {0: 'Fruit; Banana Vendor',
1: 'Blendor :Kaka Orange',
2: 'piercing Fruit Banana takes a lot',
3: 'bullet jacket gun'}})
df_input
For every word in Keyword column,
- if any of it appears in Returns column, Score = 1
- if none of it appears in Returns column, Score = 0
- if any of it appears in first half of the words in Returns column, Score_before = 1
- if any of it appears in second half of the words in Returns column, Score_after = 1
Output:
import pandas as pd
df_output = pd.DataFrame({'Keyword': {0: 'apple banana, orange',
1: 'apple orange ?banana "',
2: 'potato, piercing pot hole',
3: 'armor hard known'},
'Returns': {0: 'Fruit; Banana Vendor',
1: 'Blendor :Kaka Orange',
2: 'piercing Fruit Banana takes a lot',
3: 'bullet jacket gun'},
'Score': {0: 1, 1: 1, 2: 1, 3: 0},
'Score_before': {0: 0, 1: 0, 2: 1, 3: 0},
'Score_after': {0: 0, 1: 1, 2: 0, 3: 0}})
df_output
Original data frame has a million rows, how do I even tokenize the words efficiently? Should I use string operations instead?
(I've used from nltk.tokenize import word_tokenize before, but how to apply it on the whole data frame if that's the way?)
Edit: My custom function for tokenization:
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
import string
def tokenize(s):
translator = str.maketrans('', '', string.punctuation)
s = s.translate(translator)
s = word_tokenize(s)
return s
tokenize('Finity: Stocks%, Direct$ MF, ETF')

