pandas教程:USDA Food Database USDA食品数据库

文章目录

  • 14.4 USDA Food Database(美国农业部食品数据库)

14.4 USDA Food Database(美国农业部食品数据库)

这个数据是关于食物营养成分的。存储格式是JSON,看起来像这样:

{"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" },...]
}     

每种食物都有一系列特征,其中有两个list,protionsnutrients。我们必须把这样的数据进行处理,方便之后的分析。

这里使用python内建的json模块:

import pandas as pd
import numpy as np
import json
pd.options.display.max_rows = 10
db = json.load(open('../datasets/usda_food/database.json'))
len(db)
6636
db[0].keys()
dict_keys(['manufacturer', 'description', 'group', 'id', 'tags', 'nutrients', 'portions'])
db[0]['nutrients'][0]
{'description': 'Protein','group': 'Composition','units': 'g','value': 25.18}
nutrients = pd.DataFrame(db[0]['nutrients'])
nutrients
descriptiongroupunitsvalue
0ProteinCompositiong25.180
1Total lipid (fat)Compositiong29.200
2Carbohydrate, by differenceCompositiong3.060
3AshOtherg3.280
4EnergyEnergykcal376.000
...............
157SerineAmino Acidsg1.472
158CholesterolOthermg93.000
159Fatty acids, total saturatedOtherg18.584
160Fatty acids, total monounsaturatedOtherg8.275
161Fatty acids, total polyunsaturatedOtherg0.830

162 rows × 4 columns

当把由字典组成的list转换为DataFrame的时候,我们可以吹创业提取的list部分。这里我们提取食品名,群(group),ID,制造商:

info_keys = ['description', 'group', 'id', 'manufacturer']
info = pd.DataFrame(db, columns=info_keys)
info[:5]
descriptiongroupidmanufacturer
0Cheese, carawayDairy and Egg Products1008
1Cheese, cheddarDairy and Egg Products1009
2Cheese, edamDairy and Egg Products1018
3Cheese, fetaDairy and Egg Products1019
4Cheese, mozzarella, part skim milkDairy and Egg Products1028
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.5+ 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
Pork Products                        328
Fruits and Fruit Juices              328
Name: group, dtype: int64

这里我们对所有的nutrient数据做一些分析,把每种食物的nutrient部分组合成一个大表格。首先,把每个食物的nutrient列表变为DataFrame,添加一列为id,然后把id添加到DataFrame中,接着使用concat联结到一起:

# 先创建一个空DataFrame用来保存最后的结果
# 这部分代码运行时间较长,请耐心等待
nutrients_all = pd.DataFrame()for food in db:nutrients = pd.DataFrame(food['nutrients'])nutrients['id'] = food['id']nutrients_all = nutrients_all.append(nutrients, ignore_index=True)

译者:虽然作者在书中说了用concat联结在一起,但我实际测试后,这个concat的方法非常耗时,用时几乎是append方法的两倍,所以上面的代码中使用了append方法。

一切正常的话出来的效果是这样的:

nutrients_all
descriptiongroupunitsvalueid
0ProteinCompositiong25.1801008
1Total lipid (fat)Compositiong29.2001008
2Carbohydrate, by differenceCompositiong3.0601008
3AshOtherg3.2801008
4EnergyEnergykcal376.0001008
..................
389350Vitamin B-12, addedVitaminsmcg0.00043546
389351CholesterolOthermg0.00043546
389352Fatty acids, total saturatedOtherg0.07243546
389353Fatty acids, total monounsaturatedOtherg0.02843546
389354Fatty acids, total polyunsaturatedOtherg0.04143546

389355 rows × 5 columns

这个DataFrame中有一些重复的部分,看一下有多少重复的行:

nutrients_all.duplicated().sum() # number of duplicates
14179

把重复的部分去掉:

nutrients_all = nutrients_all.drop_duplicates()
nutrients_all
descriptiongroupunitsvalueid
0ProteinCompositiong25.1801008
1Total lipid (fat)Compositiong29.2001008
2Carbohydrate, by differenceCompositiong3.0601008
3AshOtherg3.2801008
4EnergyEnergykcal376.0001008
..................
389350Vitamin B-12, addedVitaminsmcg0.00043546
389351CholesterolOthermg0.00043546
389352Fatty acids, total saturatedOtherg0.07243546
389353Fatty acids, total monounsaturatedOtherg0.02843546
389354Fatty acids, total polyunsaturatedOtherg0.04143546

375176 rows × 5 columns

为了与info_keys中的groupdescripton区别开,我们把列名更改一下:

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.5+ KB
col_mapping = {'description' : 'nutrient','group': 'nutgroup'}
nutrients_all = nutrients_all.rename(columns=col_mapping, copy=False)
nutrients_all
nutrientnutgroupunitsvalueid
0ProteinCompositiong25.1801008
1Total lipid (fat)Compositiong29.2001008
2Carbohydrate, by differenceCompositiong3.0601008
3AshOtherg3.2801008
4EnergyEnergykcal376.0001008
..................
389350Vitamin B-12, addedVitaminsmcg0.00043546
389351CholesterolOthermg0.00043546
389352Fatty acids, total saturatedOtherg0.07243546
389353Fatty acids, total monounsaturatedOtherg0.02843546
389354Fatty acids, total polyunsaturatedOtherg0.04143546

375176 rows × 5 columns

上面所有步骤结束后,我们可以把infonutrients_all合并(merge):

ndata = pd.merge(nutrients_all, 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.iloc[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

我们可以对食物群(food group)和营养类型(nutrient type)分组后,对中位数进行绘图:

result = ndata.groupby(['nutrient', 'fgroup'])['value'].quantile(0.5)
%matplotlib inline
result['Zinc, Zn'].sort_values().plot(kind='barh', figsize=(10, 8))

在这里插入图片描述

我们还可以找到每一种营养成分含量最多的食物是什么:

by_nutrient = ndata.groupby(['nutgroup', 'nutrient'])get_maximum = lambda x: x.loc[x.value.idxmax()]
get_minimum = lambda x: x.loc[x.value.idxmin()]max_foods = by_nutrient.apply(get_maximum)[['value', 'food']]# make the food a little smaller
max_foods.food = max_foods.food.str[:50]

因为得到的DataFrame太大,这里只输出'Amino Acids'(氨基酸)的营养群(nutrient group):

max_foods.loc['Amino Acids']['food']
nutrient
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...                        
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...
Name: food, Length: 19, dtype: object

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/228051.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

OpenHarmony亮相MTSC 2023 | 质量效率共进,赋能应用生态发展

11月25日&#xff0c;MTSC 2023第十二届中国互联网测试开发大会在深圳登喜路国际大酒店圆满举行。大会以“软件质量保障体系和测试研发技术交流”为主要目的&#xff0c;旨在为行业搭建一个深入探讨和交流的桥梁和平台。OpenAtom OpenHarmony&#xff08;简称“OpenHarmony”&a…

Linux系统编程:文件系统总结

目录和文件 获取文件属性 获取文件属性有如下的系统调用&#xff0c;下面逐个来分析。 stat:通过文件路径获取属性&#xff0c;面对符号链接文件时获取的是所指向的目标文件的属性 从上图中可以看到stat函数接收一个文件的路径字符串&#xff08;你要获取哪个文件的属性&a…

零基础学Python第三天||写一个简单的程序

通过对四则运算的学习&#xff0c;已经初步接触了Python中内容&#xff0c;如果看官是零基础的学习者&#xff0c;可能有点迷惑了。难道敲几个命令&#xff0c;然后看到结果&#xff0c;就算编程了&#xff1f;这也不是那些能够自动运行的程序呀&#xff1f; 的确。到目前为止…

07-学成在线修改/查询课程的基本信息和营销信息

修改/查询单个课程信息 界面原型 第一步: 用户进入课程列表查询页面,点击编辑按钮编辑课程的相关信息 第二步: 进入编辑界面显示出当前编辑课程的信息,其中课程营销信息不是必填项,修改成功后会自动进入课程计划编辑页面 查询课程信息 请求/响应数据模型 使用Http Client测…

蓝桥杯day02——第三大的数

题目 给你一个非空数组&#xff0c;返回此数组中 第三大的数 。如果不存在&#xff0c;则返回数组中最大的数。 示例 1&#xff1a; 输入&#xff1a;[3, 2, 1] 输出&#xff1a;1 解释&#xff1a;第三大的数是 1 。 示例 2&#xff1a; 输入&#xff1a;[1, 2] 输出&…

osgFX扩展库-异性光照、贴图、卡通特效(1)

本章将简单介绍 osgFX扩展库及osgSim 扩展库。osgFX库用得比较多,osgSim库不常用&#xff0c;因此&#xff0c;这里只对这个库作简单的说明。 osgFX扩展库 osgFX是一个OpenSceneGraph 的附加库&#xff0c;是一个用于实现一致、完备、可重用的特殊效果的构架工具&#xff0c;其…

雷达公式实现(matlab)

雷达公式实现 代码来源&#xff1a;《雷达系统分析与设计(MATLAB版)(第三版)》 function [snr] radar_eq(pt,freq,g,sigma,b,nf,loss,range) % This program implements Eq.(1.63) %% Inputs:% pt——峰值功率&#xff0c;W% freq——雷达中心频率&#xff0c;Hz% g——天线…

ZKP15.2 Formal Methods in ZK (Part I)

ZKP学习笔记 ZK-Learning MOOC课程笔记 Lecture 15: Secure ZK Circuits via Formal Methods (Guest Lecturer: Yu Feng (UCSB & Veridise)) 15.2 Formal Methods in ZK (Part I) Circuits Workflow Source Code: Witness Generation and ConstraintsWitness Generatio…

SpringCloudAlibaba之Nacos的持久化和高可用——详细讲解

目录 一、Nacos持久化 1.持久化说明 2.安装mysql数据库5.6.5以上版本(略) 3.修改配置文件 二、nacos高可用 1.集群说明 2.nacos集群架构图 2.集群搭建注意事项 3.集群规划 4.搭建nacos集群 5.安装Nginx 6.配置nginx conf配置文件 7.启动nginx进行测试即可 一、Nacos持久…

C语言——数组转换

将的两行三列数组转换为三行两列的数组 #define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h> int main() {int a[2][3]{{1,2,3},{4,5,6}};int b[3][2],i,j;for ( i 0; i <1; i){for ( j 0; j <2; j){printf("%5d",a[i][j]);b[j][i]a[i][j];}printf(&…

国标GB28181安防监控平台EasyCVR周界入侵AI算法检测方案

在城市管理和公共安全领域&#xff0c;安全视频监控的重要性日益凸显。AI视频智能分析平台基于深度学习和计算机视觉技术&#xff0c;利用AI入侵算法&#xff0c;能够实时、精准地监测周界入侵行为。 TSINGSEE青犀在视频监控及AI视频智能分析领域拥有深厚的技术积累和丰富的实…

idea创建spring boot项目,java版本只能选择17和21

1.问题描述 java版本为"11.0.20"&#xff0c;idea2023创建spring boot项目时&#xff08;File->Project->Spring Initializr&#xff09;&#xff0c;java版本无法选择11&#xff0c;导致报错&#xff0c;如下图所示&#xff1a; 2.原因 spring2.X版本在2023…