美国农业部(USDA)制作了一份有关食物营养信息的数据库。
{ "id": 21441,
"description": "KENTUCKY FRIED CHICKEN, Fried Chicken, EXTRA CRISPY, Wing, meat and skin with breading",
"tags": ["KFC"],
"manufacturer": "Kentucky Fried Chicken",
"group": "Fast Foods",
"portions": [{"amount": 1,
"unit": "wing, with skin",
"grams": 68.0
...
}, ],
"nutrients": [ { "value":20.8,
"units": "g",
"description": "Protein",
"group": "Composition" },
...
] }
每种食物都带有若干标识性属性以及两个有关营养成分和分量的列表
import json
db = json.load(open('datasets/usda_food/database.json'))

b中的每个条目都是一个含有某种食物全部数据的字典。nutrients字段是一个字典列表,其中的每个字典对应一种营养成分
nutrients = pd.DataFrame(db[0]['nutrients'])
info_keys = ['description', 'group', 'id', 'manufacturer']
info = pd.DataFrame(db, columns=info_keys)

通过value_counts,你可以查看食物类别的分布情况
pd.value_counts(info.group)[:10]

首先,将各食物的营养成分列表转换为一个DataFrame,并添加一个表示编号的列,然后将该DataFrame添加到一个列表中。后通过concat将这些东西连接起来就可以了。由于两个DataFrame对象中都有”group”和”description”, 需要对它们进行重命名。
col_mapping = {'description' : 'food','group' : 'fgroup'}
info = info.rename(columns=col_mapping, copy=False)
nutrients = []
for rec in db:
fnuts = pd.DataFrame(rec['nutrients'])
fnuts['id'] = rec['id']
nutrients.append(fnuts)
nutrients = pd.concat(nutrients,ignore_index = True)
col_mapping = {'description' : 'nutrient','group' : 'nutgroup'}
nutrients = nutrients.rename(columns=col_mapping, copy=False)

将info跟nutrients合并起来
ndata = pd.merge(nutrients, info, on='id', how='outer')

根据食物分类和营养类型画出一张中位值图
result = ndata.groupby(['nutrient', 'fgroup'])['value'].quantile(0.5)
result['Zinc, Zn'].sort_values().plot(kind='barh')

网友评论