数据分析实战—食物营养信息

1.实战内容

(1) 导入该农业部门食物营养数据的 JSON 数据文件;

python 复制代码
# 导入库
import pandas as pd
import json

db = json.load(open('foods-2011-10-03.json'))
print(type(db))
print(type(db[0]))
print(type(db[0]['nutrients']))
print(len(db[0]['nutrients']))
print(type(db[0]['nutrients'][0]))

(2) 查看食物营养数据集的记录数和字段属性名;

python 复制代码
print('数据集的记录数为:',len(db))
print('数据集的全部属性为:',db[0].keys())

(3) 查看食物营养数据集中营养成分(nutrients)所包含的信息,并将营养成分的列表数据生成DataFrame

(4) 使用 DataFrame 创建包含食物的 description、group、id、manufacturer 等信息表,并分析食物类别(group)的分布情况,提示每个食品类别的个数;

python 复制代码
info_keys = ['description', 'group', 'id', 'manufacturer']
info = pd.DataFrame(db, columns=info_keys)
print('食物信息:\n',info.head())
print('食物类别分布信息:\n',pd.value_counts(info.group))
python 复制代码
info.head()

(5) 先创建食物营养数据集中的全部食物营养成分(nutrients)数据表,然后再进行数据分析;

python 复制代码
#查看食物类别的种类个数
xx=info['group']
xx1=xx.drop_duplicates(keep='first')
print('种类个数:',xx1.count())
print(xx1)

#(5)将全部的营养数据整合放在一个列表中
nutrients = []
for rec in db:
   fnuts =pd.DataFrame(rec['nutrients'])
#给fnuts表添加一列数据,将每条的id添加到fnuts的id
   fnuts['id'] = rec['id']
   nutrients.append(fnuts)

nutrients_all=pd.concat(nutrients, ignore_index=True)
nutrients_all
python 复制代码
pd.value_counts(nutrients_all.description)
python 复制代码
pd.value_counts(nutrients_all.group)

(6) 对全部食物营养成分数据进行去重复值操作;

python 复制代码
print(nutrients_all.duplicated().sum())
#删除重复项
nutrients_new = nutrients_all.drop_duplicates()
print(nutrients_new)

(7) 将包含食物的名称、分类、编号、制造商等信息表与食物营养成分数据表合并。

python 复制代码
col_mapping = {'description' : 'food','group' : 'fgroup'}
info = info.rename(columns=col_mapping, copy=False)
print('info信息\n',info)
col_mapping = {'description' : 'nutrient','group' : 'nutgroup'}
nutrients_new = nutrients_new.rename(columns=col_mapping, copy=False)
print('营养信息\n',nutrients_new)
#将info表与nutrients表合并
ndata = pd.merge(nutrients_new, info, on='id', how='outer')
print('合并信息\n',ndata)

2.数据集下载

https://gitee.com/qxh200000/c_-code/commit/ca6f117a3d02a1e3195bc2d742be86eb901c7e22

相关推荐
吴佳浩3 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
superman超哥4 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q5 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A5 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
徐先生 @_@|||5 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
Mqh1807626 小时前
day45 简单CNN
python
MatrixOrigin6 小时前
在数据库里玩“平行宇宙”:MatrixOne Data Branch 让数据也拥有Git 的分支/合并/对比/回滚(含跨集群同步)
git·sql·数据分析
学习者0076 小时前
python 下载离线库方法
python
声声codeGrandMaster6 小时前
AI之模型提升
人工智能·pytorch·python·算法·ai
魔镜前的帅比7 小时前
多 Agent 架构:Coordinator + Worker 模式
python·ai