USDA食品數(shù)據(jù)庫分析

%pwd
u'/Users/zhongyaode'
import numpy as np
import pandas as pd
path='/Users/zhongyaode/'
import  json
from pandas import Series,DataFrame
#加載數(shù)據(jù)
db = json.load(open('/Users/zhongyaode/pythonbook/ch07/foods-2011-10-03.json'))
len(db)
6636
#db每個條目中都是一個含有某種食物全部數(shù)據(jù)的字典, nutrients字段是一個字典列表,
#其中的每個字典對應(yīng)一種營養(yǎng)成分
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]

#在將字典列表轉(zhuǎn)換為DataFrame時,可以只抽取其中的一部分字段,這里取出
#食物的名稱、分類、編號、以及制造商等信息

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

info[:5]

查看info的統(tǒng)計信息

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
#為了對全部營養(yǎng)數(shù)據(jù)做一些分析,最簡單的辦法是將所有食物的營養(yǎng)成分整合到一個大表中
#分幾步完成,首先,將各食物的營養(yǎng)成分列表轉(zhuǎn)換成為一個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
#根據(jù)營養(yǎng)分類得出的鋅中位值
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
#現(xiàn)在可知道,各營養(yǎng)成分最為豐富的食物是什么
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 相聚之后,便是離散。送走了閨蜜和家人之后,一個人在突然冷清下來的屋子里坐了很久,很多時候我們就是在這樣一次又一次見...
    姚詩竹閱讀 361評論 0 0
  • 1、settimeout不要嵌套;2、settimeout最好用變量的形式,可以看到與其他延遲的關(guān)聯(lián);3、屏幕適配...
    yyshang閱讀 203評論 0 0
  • 親愛的寶寶: 你好! “快看,快看,寶寶可以扶著東西站起來了”媽媽從QQ上發(fā)來你站立的圖片,并敲來一排急促的字,字...
    日落半林閱讀 300評論 0 5
  • 如果你有我前幾天沒發(fā)圈的感覺,那就對了。而且感謝您對小女子的關(guān)注。感恩有你,我的成長才有更多的動力。是的!前幾天心...
    瀞好如琳閱讀 203評論 0 0