USDA食品数据库分析

%pwd
u'/Users/zhongyaode'
import numpy as np
import pandas as pd
path='/Users/zhongyaode/'
import  json
from pandas import Series,DataFrame
#加载数据
db = json.load(open('/Users/zhongyaode/pythonbook/ch07/foods-2011-10-03.json'))
len(db)
6636
#db每个条目中都是一个含有某种食物全部数据的字典, nutrients字段是一个字典列表,
#其中的每个字典对应一种营养成分
db[0].keys()
[u'portions',
 u'description',
 u'tags',
 u'nutrients',
 u'group',
 u'id',
 u'manufacturer']
db[0]['nutrients'][0]
{u'description': u'Protein',
 u'group': u'Composition',
 u'units': u'g',
 u'value': 25.18}
nutrients=DataFrame(db[0]['nutrients'])

nutrients[0:7]

#在将字典列表转换为DataFrame时,可以只抽取其中的一部分字段,这里取出
#食物的名称、分类、编号、以及制造商等信息

info_keys=['description','group','id','manufacturer']
info=DataFrame(db,columns=info_keys)

info[:5]

查看info的统计信息

info.describe()

#查看info字典的基本信息
info.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6636 entries, 0 to 6635
Data columns (total 4 columns):
description     6636 non-null object
group           6636 non-null object
id              6636 non-null int64
manufacturer    5195 non-null object
dtypes: int64(1), object(3)
memory usage: 207.4+ KB
#通过value_counts查看食物类别的分布情况
pd.value_counts(info.group)[:10]
Vegetables and Vegetable Products    812
Beef Products                        618
Baked Products                       496
Breakfast Cereals                    403
Legumes and Legume Products          365
Fast Foods                           365
Lamb, Veal, and Game Products        345
Sweets                               341
Fruits and Fruit Juices              328
Pork Products                        328
Name: group, dtype: int64
pd.value_counts(info.description)[:3]
Bread, pound cake type, pan de torta salvadoran                                               1
MISSION FOODS, MISSION Flour Tortillas, Soft Taco, 8 inch                                     1
Lamb, domestic, shoulder, arm, separable lean and fat, trimmed to 1/8 fat, cooked, broiled    1
Name: description, dtype: int64
#为了对全部营养数据做一些分析,最简单的办法是将所有食物的营养成分整合到一个大表中
#分几步完成,首先,将各食物的营养成分列表转换成为一个DateFrame,并添加一个个表示
#编号的列,然后将该DataFrame添加到一个列表中,最后通过concat将这些东西链接起来
nutrients=[]
for rec in db:
    fnuts=DataFrame(rec['nutrients'])
    fnuts['id']=rec['id']
    nutrients.append(fnuts)

nutrients=pd.concat(nutrients,ignore_index=True)
nutrients.duplicated().sum()
14179
nutrients=nutrients.drop_duplicates()
nutrients.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 375176 entries, 0 to 389354
Data columns (total 5 columns):
description    375176 non-null object
group          375176 non-null object
units          375176 non-null object
value          375176 non-null float64
id             375176 non-null int64
dtypes: float64(1), int64(1), object(3)
memory usage: 17.2+ MB
#两个DataFrame对象中都有'group'和'description',为了明确到底谁是谁
#对他们进行重命名
col_mapping={'description':'food','group':'fgroup'}
info=info.rename(columns=col_mapping,copy=False)
info.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6636 entries, 0 to 6635
Data columns (total 4 columns):
food            6636 non-null object
fgroup          6636 non-null object
id              6636 non-null int64
manufacturer    5195 non-null object
dtypes: int64(1), object(3)
memory usage: 207.4+ KB
col_mapping={'description':'nutrient',\
             'group':'nutgroup'}

nutrients[:1]

nutrients=nutrients.rename(columns=col_mapping,copy=False)
#nutrients.info()
#nutrients=nutrients.rename(columns=col_maping,copy=False)
nutrients.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 375176 entries, 0 to 389354
Data columns (total 5 columns):
nutrient    375176 non-null object
nutgroup    375176 non-null object
units       375176 non-null object
value       375176 non-null float64
id          375176 non-null int64
dtypes: float64(1), int64(1), object(3)
memory usage: 17.2+ MB

nutrients[:4]

info[0:2]

#将info 和nutrients合并
ndata=pd.merge(nutrients,info,on='id',how='outer')
ndata.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 375176 entries, 0 to 375175
Data columns (total 8 columns):
nutrient        375176 non-null object
nutgroup        375176 non-null object
units           375176 non-null object
value           375176 non-null float64
id              375176 non-null int64
food            375176 non-null object
fgroup          375176 non-null object
manufacturer    293054 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 25.8+ MB
ndata.ix[30000]
nutrient                                       Glycine
nutgroup                                   Amino Acids
units                                                g
value                                             0.04
id                                                6158
food            Soup, tomato bisque, canned, condensed
fgroup                      Soups, Sauces, and Gravies
manufacturer                                          
Name: 30000, dtype: object
#根据营养分类得出的锌中位值
result=ndata.groupby(['nutrient','fgroup'])['value'].quantile(0.5)

%pylab inline
b=result['Zinc, Zn'].order().plot(kind='barh')


Populating the interactive namespace from numpy and matplotlib


/Users/zhongyaode/anaconda/envs/py/lib/python2.7/site-packages/IPython/core/magics/pylab.py:161: UserWarning: pylab import has clobbered these variables: ['info', 'rec']
`%matplotlib` prevents importing * from pylab and numpy
  "\n`%matplotlib` prevents importing * from pylab and numpy"
/Users/zhongyaode/anaconda/envs/py/lib/python2.7/site-packages/ipykernel/__main__.py:2: FutureWarning: order is deprecated, use sort_values(...)
  from ipykernel import kernelapp as app
output_40_2.png
#现在可知道,各营养成分最为丰富的食物是什么
by_nutrient=ndata.groupby(['nutgroup','nutrient'])
get_maximum=lambda x:x.xs(x.value.idxmax())
get_minimun=lambda x:x.xs(x.value.idxmin())
max_foods=by_nutrient.apply(get_maximum)[['value','food']]
#让food小点
max_foods=max_foods.food.str[:50]
max_foods[:20]
nutgroup     nutrient        
Amino Acids  Alanine                             Gelatins, dry powder, unsweetened
             Arginine                                 Seeds, sesame flour, low-fat
             Aspartic acid                                     Soy protein isolate
             Cystine                  Seeds, cottonseed flour, low fat (glandless)
             Glutamic acid                                     Soy protein isolate
             Glycine                             Gelatins, dry powder, unsweetened
             Histidine                  Whale, beluga, meat, dried (Alaska Native)
             Hydroxyproline      KENTUCKY FRIED CHICKEN, Fried Chicken, ORIGINA...
             Isoleucine          Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Leucine             Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Lysine              Seal, bearded (Oogruk), meat, dried (Alaska Na...
             Methionine                      Fish, cod, Atlantic, dried and salted
             Phenylalanine       Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Proline                             Gelatins, dry powder, unsweetened
             Serine              Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Threonine           Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Tryptophan           Sea lion, Steller, meat with fat (Alaska Native)
             Tyrosine            Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
             Valine              Soy protein isolate, PROTEIN TECHNOLOGIES INTE...
Composition  Adjusted Protein               Baking chocolate, unsweetened, squares
Name: food, dtype: object
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 相聚之后,便是离散。送走了闺蜜和家人之后,一个人在突然冷清下来的屋子里坐了很久,很多时候我们就是在这样一次又一次见...
    姚诗竹阅读 351评论 0 0
  • 1、settimeout不要嵌套;2、settimeout最好用变量的形式,可以看到与其他延迟的关联;3、屏幕适配...
    yyshang阅读 200评论 0 0
  • 亲爱的宝宝: 你好! “快看,快看,宝宝可以扶着东西站起来了”妈妈从QQ上发来你站立的图片,并敲来一排急促的字,字...
    日落半林阅读 287评论 0 5
  • 如果你有我前几天没发圈的感觉,那就对了。而且感谢您对小女子的关注。感恩有你,我的成长才有更多的动力。是的!前几天心...
    瀞好如琳阅读 196评论 0 0