NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Python > Using Data to Identify harmful ingredients and added sugars in food

Using Data to Identify harmful ingredients and added sugars in food

Fouad Yared
Posted on May 14, 2017

The skills the authors demonstrated here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Are there harmful ingredients in your food? How about added sugars? We will be using data collected to see what ingredients are harmful and which have extra sugars.

The harmful ingredients found in various foods may cause cancer, reproductive problems, or developmental problems. In California, a warning is found on foods if they cause any of these concerns (it's known as Proposition 65). There is a summary of six of these harmful ingredients at the end of this article, in a section titled "Additional Information."

Many foods contain added sugar. As a result, they are major sources of empty calories, that is calories that deliver no nutritional benefits. While fruits also contain sugar, that natural source tends to also deliver vitamins that the body needs. By July 2018, all food manufacturers must note on their nutrition labels how many grams of added sugars are found in their product, as noted on the FDA's website.

The Environmental Working Group has a cornucopia of useful information on their website (ewg.org).  In addition to reviews, the site includes detailed information on ingredients and nutrition facts for thousands of foods. The structure of the EWG website is divided into categories, subcategories, and, finally, individual foods. I scraped the data to find out which foods contain the most harmful ingredients and added sugars.

I decided to use Scrapy, a package in Python, to scrape ewg.org. With Scrapy, a user tells the spider where to visit and where to extract the data from.

Item 1: The main page of ewg.org/foodscores shows all the categories and subcategories of food.

For each piece of data, an individual xpath was created, which notes where the data is located on the web page. The items extracted were the categories, subcategories, scores, nutrients, and ingredients.

Starting on ewg.org/foodscores, the categories and subcategories were extracted through their respective xpaths. Scraping this website did not provide any severe challenges such as re-routing to other sites or problems due to prohibited scraping.

Item 2: The secondary page is where a listing of many items in a category or subcategory can be found.

The issues that were resolved included finding well-hidden xpaths, creating a list of the xpaths of categories and subcategories for the spider to visit (since four categories did not have subcategories), and extracting scores for each of the individual foods from their respective image URLs.

Item 3: The tertiary page has scores, ingredients, and nutritional information for individual foods. The scores range from 1 to 10, where 1 is the best score and 10 is the worst score.

Once I obtained all the data, I converted the serving units to grams for consistent measurements in comparing the various products. I also calculated the amount of sugar, carbohydrates, fat, and protein by weight, and I used regular expression to find the names and counts of harmful ingredients and added sugars for each observation.

The extraction resulted in a data set of 46,000 foods and their scores, ingredients, and nutrients.

To start off the analysis, I was interested in seeing the relationship of the number of ingredients in an item to the number of harmful ingredients in that item. As the scatterplot shows, when the number of ingredients increases, the number of harmful ingredients also increases.

Item 4: As the number of ingredients rises, the number of harmful ingredients also rises.

After seeing this, I was curious about differences among different categories of food.

Item 5: I created a stacked bar plot and plotted the median values of the total number of ingredients (the blue bar), the number of added sugars (the orange bar), and the number of harmful ingredients (the green bar).

Frozen food, baked goods (including breads, cakes, and pastries) and prepared meals have the highest number of ingredients and the highest number of harmful ingredients. The average number of total ingredients is 25 and the average number of harmful ingredients is 2.

Categories with the lowest number of ingredients includes herbs, seasonings, fruits, vegetables, beans, rice, pasta, and grains.

Desserts, baked goods, candy, peanut butter, jams, jellies, and baking supplies had the most added sugars, averaging 3 to 4 added sugars each.

Then I was interested in seeing the scores of these categories and comparing those to our findings above.

In the bar plot below, we see that three of the four worst scoring foods are the foods with the highest amounts of added sugars (baking supplies, desserts, and candy). The foods with the best scores are fruits, vegetables, beans, baby food, rice, pasta, and grains.

Item 6: EWG's median scores for each food category.

To get a better understanding of the Environmental Working Group's scores, I decided to look at the score distribution for processed food.

On the left hand side, we have the distribution of minimally and moderately processed foods, which is fairly normal. Most scores are in the center (scoring a 5) and the number of foods for each score decreases as we move away from the center. We see a slight uptick on the left side, around scores 1 to 1.5, as there are many fruits and vegetables with those ratings.

On the right hand side, we have the distribution of highly processed foods, where the score is most often a 10 (the worst score). There is also a fairly stable distribution of scores from 6 to 9.

Item 7: The score distribution of minimally/moderately processed foods (left side) and the distribution of highly processed foods (right side).

Since frozen foods are tied with baked goods for the most ingredients (averaging 25 ingredients per product), I wanted to see if there were differences in the subcategories of frozen foods.

As we see here, frozen desserts and pizzas are the worst for you, but there is a quite a drop off when we look at frozen fruits and vegetables which are very good for you, despite being frozen.

Item 8: EWG's scores of Frozen Food subcategories.

After understanding the composition of the scores, I decided to find the best and worst rated foods by subcategory. I created bar plots showing the mean score by subcategory along with the count of foods in that subcategory.

Flours and corn meal, fresh fruits and vegetables, frozen fruits and vegetables, and pasta and noodles rank the highest. Flours & corn meal only had 12 reviews, as compared to a range of 389 to 1,154 reviews for the other subcategories mentioned.

Item 9: Foods with the best scores / Item 10: Count of scores for the best foods

The subcategories with the worst mean scores are baking decorations (frosting, sprinkles), half and half & creamers, processed and deli meats, and canned meat. The canned meat subcategory only has 16 reviews while the others have between 335 and 1,149 reviews.

Item 11: Foods with the worst scores / Item 12: Count of scores for the worst foods

After seeing processed meat rank high on the list for worst products, I wanted to see how many harmful ingredients are found in processed meat. As we see in the plot below, each kind of processed meat has, on average, two to three harmful ingredients in it (namely, nitrates and nitrites are found in processed meat). Processed meat should be consumed in moderation, if at all.

Item 13: Amount of harmful ingredients in various kinds of processed meat.

I also wanted to take a closer look at items that are marketed as "healthy," to see if they actually are. I decided to compare bars - cereal bars, candy bars, granola bars, and trail mix bars - to see how much sugar by weight is in each of these and how their scores compare to their sugar content.

Candy bars take the lead at 42% sugar by weight, while many others follow around 36%. Granola and trail mix bars have the least amount of sugar, 23% and 26%, respectively, yet the amount of sugar they contain is somewhat of a concern.

The scores correspond fairly well to the amount of sugar by weight, as granola and trail mix bars maintain their ranks on the bottom of the list. Other attributes making up the EWG score are how processed each item is, how many added sugars are in them, and nutritional content (if any).

Item 14: Sugar by weight for various bars (Candy, trail mix, and granola bars) / Item 15: Scores of various bars

 

An Anova test was used to test the differences in group means. Since the test resulted in a p-value less than 0.05, we reject the null value that the food subcategories are the same. In other words, it would be a very rare chance that the group means of scores among the bars are the same.

In conclusion, when deciding what to buy, know that in general, the fewer the ingredients, the better. You should check that the product is free from harmful ingredients or added sugars, you can look at the scores on ewg.org, or you can look at categories to watch out for in the stacked bar plot above.

Examples of foods that should be limited are desserts, candy, baked goods, and processed meats because they are high in harmful ingredients and added sugars.

Future research would look at sales data to see what people usually purchase, what criteria are usually evaluated and how these criteria are prioritized. I would also be interested in seeing what role demographics play in the selection of healthy or unhealthy foods and to see if convenience is a large factor in what a person purchases.

--

Additional Information:

The list of harmful ingredients includes:

  • Nitrates and nitrites, deemed carcinogens by the World Health Organization, are often added to processed meats.
  • Potassium bromate is deemed a carcinogen by the International Agency for Research on Cancer. This ingredient is banned from Brazil, Canada, and the United Kingdom, yet it can still be found in certain brands of flour and breads.
  • Propyl paraben is found in pastries. It is an endocrine disruptor linked to lowered sperm counts and decreased fertility.
  • Butylated hydroxyanisole (BHA), added to chips and preserved meat, is an item that the The National Institute of Health notes is "reasonably anticipated to be a human carcinogen".
  • Butylated hydroxytoluene (BHT), an endocrine disruptor, is found in cereal.
  • Propyl gallate is associated with tumors and may be an endocrine distruptor. It is found in sausage and lard.

For more information on each of these harmful ingredients and for information on the other six, please visit Environmental Health Watch's web page titled "Dirty Dozen Guide to Food Additives."

The code used to create this Shiny app is publicly available at gist.github.com/fouadyared

The skills I demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

About Author

Fouad Yared

Dedicated to public service, Fouad Yared has four years experience working in the non-profit world: he advocated for tenants rights at Cleveland Tenants Organization and instructed classes on basic literacy and GED preparation at the Cuyahoga County Jail....
View all posts by Fouad Yared >

Related Articles

Capstone
Catching Fraud in the Healthcare System
Capstone
The Convenience Factor: How Grocery Stores Impact Property Values
Capstone
Acquisition Due Dilligence Automation for Smaller Firms
Machine Learning
Pandemic Effects on the Ames Housing Market and Lifestyle
Machine Learning
The Ames Data Set: Sales Price Tackled With Diverse Models

Leave a Comment

Cancel reply

You must be logged in to post a comment.

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application