I have a list of words and I want to do if statement, below is my list:
list = ['camera','display','price','memory'(will have 200+ words in the list)]
Here is my code:
def check_it(sentences):
if 'camera' in sentences and 'display' in sentences and 'price' in sentences:
return "Camera/Display/Price"
if 'camera' in sentences and 'display' in sentences:
return "Camera/Display"
...
return "Others"
h.loc[:, 'Category'] = h.Mention.apply(check_it)
There will be too many combinations for these and also I want to have the words return to row individually. Does anyone know how to make this sample and return the word individually instead of doing 'camera/display/price'?
Use str.findall by regex - join all values of lists with |, last str.join values by /:
df = pd.DataFrame({'Mention':['camera in sentences and display in sentences',
'camera in sentences price']})
L = ['camera','display','price','memory']
pat = '|'.join(r"\b{}\b".format(x) for x in L)
df['Category'] = df['Mention'].str.findall(pat).str.join('/')
print (df)
Mention Category
0 camera in sentences and display in sentences camera/display
1 camera in sentences price camera/price
Another solution with list comprehension, also for list use generator with join:
df['Category1'] = [[y for y in x.split() if y in L] for x in df['Mention']]
df['Category2'] = ['/'.join(y for y in x.split() if y in L) for x in df['Mention']]
print (df)
Mention Category1 \
0 camera in sentences and display in sentences [camera, display]
1 camera in sentences price [camera, price]
Category2
0 camera/display
1 camera/price
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With