Lesson 38 · Real-World Data Analytics
Python Data Analytics #38: Global Food Consumption & Diet Footprint in Python
A real global nutrition dataset, one hundred thirty real countries, eleven real food categories, real consumption and real carbon footprint per person.
- CourseReal-World Data Analytics
- Lesson38 of 100
- FormatJupyter notebook · 30 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- food_consumption_raw.csv preview51.0 KB
📓 Full notebook
Download .ipynbData Analytics 100, Video 38: Real Global Food Consumption and Diet Footprint#
- Video thirty-eight of the hundred-video real-world data analytics series.
- A real global nutrition dataset, one hundred thirty real countries, eleven real food categories, real consumption and real carbon footprint per person.
- Let's get into it.
This lesson is for learners who want to practise grouping, ranking and reshaping a tidy "long" table, where each row is one country and one food category. The question it answers is one that climate and food analysts ask all the time: which countries and which foods drive the carbon footprint of what people eat?
The dataset, food_consumption_raw.csv, has four columns: country, food_category (such as Beef, Rice or Milk - inc. cheese), consumption (food eaten per person per year) and co2_emmission (the CO2 linked to that food, in kilograms per person per year, as the chart labels state). Note the column name keeps its original misspelling, so type it exactly.
In this lesson you will:
- total consumption and emissions by country and by food category
- compute carbon intensity, the CO2 produced per kilogram of food
- compare animal and plant foods with
isin()filters - pivot a long table into a wide country-by-category view
You should be comfortable with pandas groupby, sort_values and boolean filtering; see earlier lessons in the series if not.
Part 1: A Real Global Nutrition Dataset#
Start by confirming the size of the table so later totals have a reference point. The code imports pandas, numpy and matplotlib, reads the CSV with pd.read_csv, and shows .shape. The output, (1430, 4), means 1,430 rows and 4 columns. With 130 countries and 11 food categories, 130 times 11 is exactly 1,430, so every country appears to have one row for every category. That is a useful structure to confirm, and the notebook checks it properly later.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
food = pd.read_csv('food_consumption_raw.csv')
food.shape
Part 2: Real Data Preview#
Checking data types tells you whether numeric columns were read as numbers or as text. The code calls food.head(5) and then food.dtypes; only the last expression is displayed, so the output shows types rather than rows. country and food_category are object (text), while consumption and co2_emmission are float64, meaning decimal numbers. That is what you want: you can sum and average them directly. If a numeric column showed as object, you would need to clean it first.
food.head(5)
food.dtypes
Part 3: Real Missing Data Check#
Missing values would quietly lower every total, so it is worth a quick check even on a small table. isna().sum() counts missing entries per column. The output shows 0 in all four columns, so the data is complete. A zero here does not rule out other quality issues, such as genuine zeros or impossible values; the notebook looks at zero-consumption rows near the end.
food.isna().sum()
Part 4: Real Countries and Categories#
Knowing the exact category labels saves typos when you filter later. The first line counts distinct countries and categories, but only the last expression is displayed, so the output is the array from unique(): the 11 food categories, from Pork and Poultry through to Soybeans and Nuts inc. Peanut Butter. Copy labels like 'Milk - inc. cheese' and 'Lamb & Goat' exactly as shown, including spaces and punctuation, or your filters will silently return nothing.
food['country'].nunique(), food['food_category'].nunique()
food['food_category'].unique()
Part 5: Real Summary Statistics#
Summary statistics show the scale and spread of both measures before you start ranking. describe() on the two numeric columns gives count, mean, standard deviation, quartiles and extremes. Consumption has a median of 8.89 but a mean of 28.1 and a maximum of 430.76, while emissions have a median of 16.53, a mean of 74.4 and a maximum of 1,712. When the mean is far above the median, a few very large values are pulling it up, so medians are often the safer typical value here.
food[['consumption', 'co2_emmission']].describe()
Part 6: Real Highest Total Food Consumption#
Totalling each country's consumption across all categories gives a rough picture of how much of these tracked foods people eat. groupby('country')['consumption'].sum() adds up the 11 rows per country, and sort_values(ascending=False) puts the largest first. Finland leads with 639.79, followed by Lithuania (555.01), Sweden (550.00), the Netherlands (534.17) and Albania (532.73). These totals only cover the 11 tracked categories, so they are not a full measure of diet.
total_consumption = food.groupby('country')['consumption'].sum().sort_values(ascending=False)
total_consumption.head(5)
Part 7: Real Lowest Total Food Consumption#
The same sorted Series also gives you the bottom of the ranking. Because total_consumption is sorted from largest to smallest, .tail(5) returns the five smallest totals. Rwanda is lowest at 40.38, with Malawi (51.00), Zambia (57.11), Mozambique (63.41) and Togo (74.32) just above. Finland's total is roughly 16 times Rwanda's. Remember that staples outside these categories, such as maize or cassava, are not counted here, which matters for many of these countries.
total_consumption.tail(5)
Part 8: Real Highest Carbon Footprint Countries#
Emissions tell a different story from volume, because foods differ hugely in their carbon cost. The code sums co2_emmission per country and sorts from highest. Argentina leads at 2,172.4 kg CO2 per person per year, followed by Australia (1,938.66), Albania (1,777.85), New Zealand (1,750.95) and Iceland (1,731.36). Finland, the top consumer, is not in this top five, which hints that what people eat matters more than how much.
total_co2 = food.groupby('country')['co2_emmission'].sum().sort_values(ascending=False)
total_co2.head(5)
Part 9: Real Lowest Carbon Footprint Countries#
The lowest-footprint countries are mostly the same places with the lowest consumption. total_co2.tail(5) shows Mozambique lowest at 141.4, then Rwanda (181.63), Togo (188.09), Liberia (203.38) and Malawi (207.94). Comparing this list with the low-consumption list is a quick check that the two measures broadly agree at this end, even though they diverge at the top.
total_co2.tail(5)
Part 10: Real Top Emitters Chart#
A chart makes the top emitters easier to compare than a list of numbers. The code takes the top 10 from total_co2, re-sorts them in ascending order so the largest bar sits at the top, and draws a horizontal bar chart with kind='barh'. It labels the axis in kilograms of CO2 per person per year, saves the figure as top_co2_countries.png and closes it, so nothing appears inline. When you open the image, look at how close the countries after Argentina are to each other.
fig, ax = plt.subplots(figsize=(10, 6))
total_co2.head(10).sort_values().plot(kind='barh', ax=ax, color='firebrick')
ax.set_xlabel('Real Total CO2 Emissions (Kg per Person per Year)')
ax.set_title('Real Highest Diet-Related Carbon Footprint by Country')
plt.tight_layout()
plt.savefig('top_co2_countries.png', dpi=100)
plt.close()
Part 11: Real Consumption by Food Category#
Switching the grouping from country to food category shows which foods make up most of what is eaten. groupby('food_category')['consumption'].sum() adds each category across all 130 countries. Milk including cheese is by far the largest at 16,350.71, followed by wheat at 9,301.44 and rice at 3,818.77. Beef totals 1,576.04 and soybeans just 111.87. Summing per-person figures across countries treats every country equally regardless of population, so read these as a comparison of categories, not global tonnages.
category_consumption = food.groupby('food_category')['consumption'].sum().sort_values(ascending=False)
category_consumption
Part 12: Real CO2 Emissions by Food Category#
Now the same grouping for emissions. Beef dominates with 48,633.26, about twice milk and cheese at 23,290.00, with lamb and goat third at 11,837.38. Wheat, despite being the second most consumed category, produces only 1,773.78. Setting this output beside the consumption totals is the key insight of the lesson: the foods eaten most are not the ones producing most emissions.
category_co2 = food.groupby('food_category')['co2_emmission'].sum().sort_values(ascending=False)
category_co2
Part 13: Real CO2 Efficiency by Category#
Carbon intensity, the CO2 produced per kilogram of food consumed, explains why volumes and emissions differ. Dividing one Series by another, category_co2 / category_consumption, lines them up by category name and divides each pair. Lamb and goat is the most carbon-intensive at 35.02, then beef at 30.86, then a big drop to pork at 3.54. Wheat is lowest at 0.19 and soybeans 0.45. So a kilogram of beef carries roughly 160 times the CO2 of a kilogram of wheat in this data.
category_ratio = (category_co2 / category_consumption).sort_values(ascending=False)
category_ratio.round(2)
Part 14: Real Efficiency Chart#
This chart turns the intensity table into a picture. category_ratio.sort_values() sorts ascending so the most intensive food ends up at the top, and kind='barh' draws horizontal bars, which suit long category names. The figure is saved to co2_efficiency_by_category.png and closed, so there is no inline output. When you open it, look for the two very long bars for lamb and goat and for beef, with every other category bunched near zero.
fig, ax = plt.subplots(figsize=(10, 6))
category_ratio.sort_values().plot(kind='barh', ax=ax, color='seagreen')
ax.set_xlabel('Real Kg CO2 per Kg Consumed')
ax.set_title('Real Carbon Intensity by Food Category')
plt.tight_layout()
plt.savefig('co2_efficiency_by_category.png', dpi=100)
plt.close()
Part 15: Real Beef Consumption vs Total Footprint#
If beef is so carbon-intensive, a country's beef consumption should go a long way to explain its total footprint. The code filters the beef rows, renames consumption to beef_consumption, turns total_co2 back into a table with reset_index(), and joins the two on country with merge. .corr() then gives the Pearson correlation. The output, 0.896, is a very strong positive relationship. Bear in mind that beef emissions are part of the total, so some of this link is built in.
beef = food[food['food_category'] == 'Beef'][['country', 'consumption']].rename(columns={'consumption': 'beef_consumption'})
beef_vs_total = total_co2.reset_index().rename(columns={'co2_emmission': 'total_co2'}).merge(beef, on='country')
beef_co2_corr = round(beef_vs_total['beef_consumption'].corr(beef_vs_total['total_co2']), 3)
beef_co2_corr
Part 16: Real Animal vs Plant Footprint Share#
Grouping categories into animal and plant foods gives one clear headline. The code defines two lists and uses isin(), which returns True for rows whose category is in the given list, to filter and sum emissions for each group. The animal share is then animal emissions divided by the combined total. The output is 92.8%: animal-based foods account for over nine tenths of tracked diet emissions. Check that your lists cover all 11 categories, or the share will be quietly wrong.
animal_categories = ['Pork', 'Poultry', 'Beef', 'Lamb & Goat', 'Fish', 'Eggs', 'Milk - inc. cheese']
plant_categories = ['Wheat and Wheat Products', 'Rice', 'Soybeans', 'Nuts inc. Peanut Butter']
animal_co2_total = food[food['food_category'].isin(animal_categories)]['co2_emmission'].sum()
plant_co2_total = food[food['food_category'].isin(plant_categories)]['co2_emmission'].sum()
animal_share = round(animal_co2_total / (animal_co2_total + plant_co2_total) * 100, 1)
animal_share
Part 17: Real Rice-Heavy Countries#
Looking within one category shows which countries rely most on a given food. The code filters for 'Rice', sorts by consumption from highest, keeps the top five rows and shows two columns. Bangladesh is highest at 171.73, then Cambodia (159.10), Vietnam (144.56), Indonesia (134.62) and Myanmar (132.80), all in South and South-East Asia. Rice has a low carbon intensity, which helps explain why heavy rice eaters do not appear among the top emitters.
rice_heavy = food[food['food_category'] == 'Rice'].sort_values('consumption', ascending=False).head(5)[['country', 'consumption']]
rice_heavy
Part 18: Real Dairy-Heavy Countries#
Dairy was the largest category by volume and second by emissions, so its heaviest consumers are worth a look. The same pattern of filter, sort and head on 'Milk - inc. cheese' gives Finland at 430.76, the Netherlands (341.47), Sweden (341.23), Switzerland (318.69) and Albania (303.72). Several of these also topped the total consumption list, which shows that dairy alone explains much of those countries' high totals.
dairy_heavy = food[food['food_category'] == 'Milk - inc. cheese'].sort_values('consumption', ascending=False).head(5)[['country', 'consumption']]
dairy_heavy
Part 19: Real Footprint Inequality Across Countries#
A single ratio summarises how unequal diet footprints are across countries. The code divides the largest total CO2 (total_co2.max()) by the smallest (total_co2.min()) and rounds. The output is 15.4, meaning Argentina's diet footprint is over fifteen times Mozambique's. Max-to-min ratios are easy to communicate but sensitive to a single extreme country; comparing the 90th and 10th percentiles is a more robust option.
footprint_ratio = round(total_co2.max() / total_co2.min(), 1)
footprint_ratio
Part 20: Real Country by Category Pivot#
Long tables are good for grouping, but a wide table with one row per country and one column per food is easier to read across. pivot_table does that: index='country' sets the rows, columns='food_category' creates a column per category, and values='consumption' fills the cells. By default it averages any repeated pairs, but here each pair appears once. The output shape (130, 11) confirms 130 countries by 11 categories.
pivot = food.pivot_table(index='country', columns='food_category', values='consumption')
pivot.shape
Part 21: Real Pivot Preview#
A quick look at the pivoted table confirms it came out as expected. pivot.head(3) shows the first three countries, which wraps across several blocks because there are 11 columns. Albania eats 303.72 of milk and cheese and 138.64 of wheat; Algeria shows 0.00 for pork, which makes sense for a mostly Muslim country; Angola has a relatively high 15.24 for fish. Reading across a row gives you one country's tracked diet at a glance.
pivot.head(3)
Part 22: Real Single Highest Consumption Record#
Finding the single largest value in the long table is a quick sanity check on the extremes. idxmax() returns the index label of the row with the highest consumption, and .loc[...] fetches that whole row. The output is Finland's milk and cheese record: 430.76 consumed and 613.57 kg of CO2. That matches the maximum in the earlier summary and the top of the dairy list, so the three views agree.
top_record = food.loc[food['consumption'].idxmax()]
top_record
Part 23: Saving the Real Enriched Dataset#
Saving a copy at a known point means you can reload clean data later without rerunning every step. to_csv with index=False writes the file without the pandas row numbers, and the code reads it back and compares shapes. The output True confirms the file holds the same number of rows and columns. Note that only food is saved, not the pivot or the grouped tables.
food.to_csv('food_consumption_cleaned.csv', index=False)
reloaded = pd.read_csv('food_consumption_cleaned.csv')
reloaded.shape == food.shape
Part 24: Real Sanity Check, Row Count#
This assertion confirms the table still has exactly 1,430 rows, matching the start of the notebook and 130 countries times 11 categories. The output is True. Checks like this are cheap to write and quickly flag any accidental filtering or duplication if you rerun the notebook on a new version of the file.
len(food) == 1430
Part 25: Real Sanity Check, No Duplicate Pairs#
Each country should have exactly one row per food category. duplicated(subset=['country', 'food_category']) marks repeats of that pair, and .sum() == 0 confirms there are none. The output np.True_ (numpy's form of True) means every country-category pair is unique. This is what allowed the pivot table to work without averaging duplicate rows together.
food.duplicated(subset=['country', 'food_category']).sum() == 0
Part 26: Real Sanity Check, Category Count#
A final structural check confirms the number of categories. nunique() counts distinct values in food_category, and the comparison with 11 returns True. If a label had a stray space or different spelling in one row, it would show up as a twelfth category and this check would fail, so it doubles as a test for inconsistent labels.
food['food_category'].nunique() == 11
Part 27: Real Category with Widest Variation#
Standard deviation measures how spread out values are; here it shows which foods vary most between countries. groupby('food_category')['consumption'].std() computes it per category, sorted from highest. Milk and cheese varies most at 93.3, then wheat at 44.2 and rice at 37.3, while soybeans vary least at 2.1. Large categories naturally have larger spreads, so for a fair comparison you could divide each by its mean (the coefficient of variation).
category_std = food.groupby('food_category')['consumption'].std().sort_values(ascending=False)
category_std.round(1)
Part 28: Real Zero-Consumption Records#
Zeros can be genuine (nobody eats that food) or a sign of missing data recorded as 0. (food['consumption'] == 0) creates a True/False Series and .sum() counts the Trues. The output is 31 rows with zero consumption, such as Algeria's pork seen in the pivot. These are plausible here, but it is worth knowing the count, because zeros pull down averages and can make ratios like CO2 per kilogram undefined.
zero_records = (food['consumption'] == 0).sum()
zero_records
Part 29: Real Top Finding Print#
Generating the headline sentence from the data keeps it accurate if the data changes. Because total_co2 is sorted descending, .index[0] gives the top country's name and .iloc[0] its value, which is rounded to one decimal. The f-string output reads that Argentina has the highest diet-related carbon footprint in this dataset, at 2,172.4 kg of CO2 per person per year.
top_footprint_country = total_co2.index[0]
top_footprint_value = round(total_co2.iloc[0], 1)
print(f'{top_footprint_country} carries the real highest diet-related carbon footprint in this dataset, at {top_footprint_value} real kilograms of CO2 per person per year.')
Part 30: Real Recap Print#
The recap pulls together the two strongest findings into one line. The f-string inserts the number of countries, the animal share and the beef correlation calculated earlier. The output says that across 130 countries, animal-based foods drove 92.8% of tracked diet emissions, and beef consumption alone correlated with total footprint at 0.896. It is a compact summary you could put at the top of a report.
print(f'Across {food["country"].nunique()} real countries, animal-based foods drove {animal_share}% of tracked diet emissions, and beef consumption alone correlated with total footprint at {beef_co2_corr}.')
Wrap-Up: What You Learned#
- This real dataset covers one hundred thirty real countries across eleven real tracked food categories, with genuinely zero missing values.
- Animal-based foods, especially beef and dairy, drove the overwhelming majority of tracked diet-related emissions, despite plant staples like rice and wheat being consumed in real larger volumes.
- Real beef consumption alone was a real strong single predictor of a real country's overall diet footprint.
- The real gap between the highest and lowest footprint countries in this dataset spans over a real fifteen-fold difference.
- Pivoting a real long dataset into a real wide country-by-category table makes cross-country diet comparisons genuinely easier to read.
- Next video: a real global health expenditure analysis, continuing this domain with a look at what countries actually spend on healthcare.
Practice on your own
- Build a second pivot table with
values='co2_emmission'and find, for each country, which food category contributes the most CO2 usingidxmax(axis=1). - Calculate each country's animal share of emissions (not just the overall figure) and list the five countries with the lowest share.
- Compute the coefficient of variation (standard deviation divided by mean) for each food category and see whether milk and cheese still varies the most.
Each exercise reuses code from this notebook with small changes. The next lesson in the series moves on to a global health expenditure analysis, looking at what countries actually spend on healthcare.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



