Skip to content

Instantly share code, notes, and snippets.

Last active Sep 12, 2020
What would you like to do?
## Reverse the mapping to match with the food values
map_dict_reverse = {val:key for key,vals in map_dict.items() for val in vals}
##==== Mapping trick: func Map() to work with Pandas SERIES; fillna = 'others'
dairy_table['Food_Category'] = dairy_table['Food'].map(map_dict_reverse).fillna('others')
index0 Milk
index1 others
index2 Milk
index3 Milk
index4 Milk
##==== Mapping trick: func Applymap() to work with Pandas DATA FRAME;
##==== keep the raw values if not defined in the dict
dairy_table.applymap(lambda x: map_dict_reverse.get(x) if x in map_dict_reverse.keys() else x)
Food Measure Grams Calories
index0 Milk 1 qt. 976 660
index1 Milk 1 qt. 984 360
index10 Cocoa 1 cup 252 235
index11 Yogurt, of partially skim. milk 1 cup 250 128
index12 Pudding 1 cup 248 275
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment