I'd like to create a column in my dataframe that checks whether the values in one column are the dictionary values of another column which comprises the dictionary keys, like so:
In [3]:
df = pd.DataFrame({'Model': ['Corolla', 'Civic', 'Accord', 'F-150'],
'Make': ['Toyota', 'Honda', 'Toyota', 'Ford']})
dic = {'Prius':'Toyota', 'Corolla':'Toyota', 'Civic':'Honda',
'Accord':'Honda', 'Odyssey':'Honda', 'F-150':'Ford',
'F-250':'Ford', 'F-350':'Ford'}
df
Out [3]:
Model Make
0 Corolla Toyota
1 Civic Honda
2 Accord Toyota
3 F-150 Ford
And after applying a function, or whatever it takes, I'd like to see:
Out [10]:
Model Make match
0 Corolla Toyota TRUE
1 Civic Honda TRUE
2 Accord Toyota FALSE
3 F-150 Ford TRUE
Thanks in advance!
Edit: I tried making a function that is passed a tuple which would be the two columns, but I don't think I'm passing the arguments correctly:
def is_match(make, model):
try:
has_item = dic[make] == model
except KeyError:
has_item = False
return(has_item)
df[['Model', 'Make']].apply(is_match)
results in:
TypeError: ("is_match() missing 1 required positional
argument: 'model'", 'occurred at index Model')
You can using map
df.assign(match=df.Model.map(dic).eq(df.Make))
Out[129]:
Make Model match
0 Toyota Corolla True
1 Honda Civic True
2 Toyota Accord False
3 Ford F-150 True
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