I have a data frame with a column named text and want to assign values in a new column if the text in the first column contains one or more substrings from a dictionary. If the text column contains a substring, I want the key of the dictionary to be assigned to the new column category.
This is what my code looks like:
import pandas as pd
some_strings = ['Apples and pears and cherries and bananas',
'VW and Ford and Lamborghini and Chrysler and Hyundai',
'Berlin and Paris and Athens and London']
categories = ['fruits', 'cars', 'capitals']
test_df = pd.DataFrame(some_strings, columns = ['text'])
cat_map = {'fruits': {'apples', 'pears', 'cherries', 'bananas'},
'cars': {'VW', 'Ford', 'Lamborghini', 'Chrysler', 'Hyundai'},
'capitals': {'Berlin', 'Paris', 'Athens', 'London'}}
The dictionary cat_map contains sets of strings as values. If the text column in test_df contains any of those words, then I want the key of the dictionary to be assigned as value to the new category column. The output dataframe should look like this:
output_frame = pd.DataFrame({'text': some_strings,
'category': categories})
Any help on this would be appreciated.