Last active
September 12, 2020 20:02
-
-
Save YiLi225/adb338baabb3fc3412ac0683669ce86f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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') | |
Out[134]: | |
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) | |
Out[139]: | |
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