数据分析:USDA食品数据库

# -*- coding: utf-8 -*-  

import json
import pandas as pd
from pandas import DataFrame

db = json.load(open('usda_food/database.json'))
#print len(db)

#print db[0].keys()

#print db[0]['nutrients'][0]

nutrients = DataFrame(db[0]['nutrients'])
#print nutrients[:7]

#取出食物名称、分类、编号以及制造商等信息
info_keys = ['description', 'group', 'id', 'manufacturer']
info = DataFrame(db, columns = info_keys)
#print info.head()

#查看食物分布情况
#print pd.value_counts(info.group)

#全部营养作分析
#营养成分制成表格
nutrients = []

for rec in db:
    funts = DataFrame(rec['nutrients'])
    funts['id'] = rec['id']
    nutrients.append(funts)
    
nutrients = pd.concat(nutrients, ignore_index = True)
#print nutrients

#查看并丢弃重复值
#print nutrients.duplicated().sum()
nutrients = nutrients.drop_duplicates()
#print nutrients

#重命名
col_mapping = {'description' : 'food' , 'group' : 'fgroup' }
info = info.rename(columns = col_mapping, copy = False)
#print info

col_mapping = {'description' : 'nutrient', 'group' : 'nutgroup'}
nutrients = nutrients.rename(columns = col_mapping, copy = False)
#print nutrients

#合并info和nutrients
ndata = pd.merge(nutrients, info, on='id', how='outer')
#print ndata.head()
#print ndata.ix[30000]

#锌中位值
result = ndata.groupby(['nutrient', 'fgroup'])['value'].quantile(0.5)
#order()按值排序
#print result['Zinc, Zn'].order().plot(kind='barh')

#查看营养之最丰富的食物
by_nutrient = ndata.groupby(['nutgroup', 'nutrient'])

get_maximum = lambda x: x.xs(x.value.idxman())
get_minimum = lambda x: x.xs(x.value.idxmin())

max_foods = by_nutrient.apply(get_maximum)[['value', 'food']]

#让food小一点
max_foods.food = max_foods.food.str[:50]
print max_foods.ix['Amino Acids']['food']

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页