I’m having difficulties trying to get this to work. So to summarize: I have a dataframe, I have a dictionary with keys of certain values in a certain dataframe value, and I want to create a new dataframe column of true/false if they match or not.
So here is an example of the data:
animal_list = ['dog', 'cat', 'dog', 'fish', 'bird', 'dog', 'bug', 'bird', 'snake']
animal_dict = {'dog': [3], 'bird': [2]}
animals = pd.DataFrame(animal_list, columns = ['Pets'])
animals
Basically I want a new column with boolean True if it matches the key, or False if not.
ALTERNATIVELY I suppose I could skip the dictionary altogether if I could create the new column with a query on if there are multiple instances of a value in existing column (‘Pets’). So it would be True for dogs and birds, but false for everything else.
UPDATE: Here is the solution I used, for others who may be searching for it. I originally had this function but was using apply method instead of map (as suggested by algebruh below)
def find_key(find_value):
for k, v in animal_dict.items():
if k == find_value:
return True
return False
animals['multiple'] = animals['Pets'].map(find_key)
>Solution :
You can simply check if animals['Pets'] isin animals_dict:
animals['multiple'] = animals['Pets'].isin(animal_dict)
Output:
Pets multiple
0 dog True
1 cat False
2 dog True
3 fish False
4 bird True
5 dog True
6 bug False
7 bird True
8 snake False