Mathew K Analytics

Lesson 45 · Real-World Data Analytics

Share vs Ratio Columns in Pandas: World Cup Fans vs Viewers | Python Data Analytics #45

A fifth completely different sport in this sports analytics domain. A real FiveThirtyEight dataset comparing every real FIFA member country's real…

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.

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 45: Real Global Soccer Fan Base Analysis#

  • Video forty-five of the hundred-video real-world data analytics series, a fifth completely different sport in this sports analytics domain.
  • A real FiveThirtyEight dataset comparing every real FIFA member country's real population, TV audience, and economic weight in the sport.
  • Let's get into it.

This lesson is for learners who want to practise working with share data and comparing countries, using football (soccer) fandom as the setting. The business question: where is the World Cup's TV audience concentrated, and does a country's audience follow its population or its economic weight?

The dataset is from FiveThirtyEight and covers 191 FIFA member countries. Each row has the country, its confederation (the regional governing body, such as UEFA for Europe or CONMEBOL for South America), and three shares of a world total, all in percent: population_share, tv_audience_share (share of the World Cup TV audience) and gdp_weighted_share (the audience share weighted by each country's economic output).

In this lesson you will:

  • profile heavily skewed share columns and rank countries with nlargest and nsmallest
  • create a gap column to find countries that watch more, or less, than their population suggests
  • compare confederations with groupby and compare two correlations
  • check that share columns add up to roughly 100%

You should be comfortable with pandas filtering, groupby and describe(); see earlier lessons in the series if not.

Part 1: A Real Global Soccer Dataset#

Every analysis starts by loading the data and confirming its size. The code imports pandas, numpy and matplotlib, reads fifa_countries_audience.csv into a DataFrame called fifa with pd.read_csv, and shows fifa.shape. The output, (191, 5), means 191 rows and 5 columns, one row per FIFA member country. Note the number 191: you will check against it again in the sanity checks, and it helps when you later add up the share columns across all countries.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fifa = pd.read_csv('fifa_countries_audience.csv')
fifa.shape
(191, 5)

Part 2: Real Data Preview#

You need to know what each column holds before calculating anything. The code calls fifa.head(5) and then fifa.columns.tolist(); Jupyter only displays the last expression, so the output is the list of five column names: country, confederation, population_share, tv_audience_share and gdp_weighted_share. The three share columns are percentages of a world total, so across all countries each should add up to about 100. That property gives you a useful check later in the lesson.

fifa.head(5)
fifa.columns.tolist()
['country',
 'confederation',
 'population_share',
 'tv_audience_share',
 'gdp_weighted_share']

Part 3: Real Missing Data Check#

Missing values can quietly break sums, averages and correlations, so you check for them early. fifa.isna() marks each missing value as True, the first .sum() counts them per column, and the second .sum() adds those counts into one total for the whole table. The output is 0, so every country has a value in every column. You can move straight to analysis without filling or dropping rows.

fifa.isna().sum().sum()
np.int64(0)

Part 4: Real Confederation Breakdown#

Confederations group countries by region, and knowing their sizes helps you interpret any comparison between them. fifa['confederation'].value_counts() counts countries per confederation. The output shows CAF (Africa) largest with 50, then UEFA (Europe) with 46, AFC (Asia) with 43, CONCACAF (North and Central America and the Caribbean) with 30, OFC (Oceania) with 12 and CONMEBOL (South America) with just 10. Small groups such as CONMEBOL and OFC can have averages driven by one or two countries, so keep these counts in mind.

fifa['confederation'].value_counts()
confederation
CAF         50
UEFA        46
AFC         43
CONCACAF    30
OFC         12
CONMEBOL    10
Name: count, dtype: int64

Part 5: Real TV Audience Distribution#

Share data is often very uneven, so you need to look at the spread before ranking. describe() on tv_audience_share shows a mean of about 0.52% but a median of just 0.1%, and at least a quarter of countries at 0. The maximum is 14.8%. When the mean is five times the median, a handful of countries hold most of the audience while most countries hold very little. For data like this, quoting the average alone would give a misleading picture of a typical country.

fifa['tv_audience_share'].describe()
count    191.000000
mean       0.523037
std        1.449535
min        0.000000
25%        0.000000
50%        0.100000
75%        0.300000
max       14.800000
Name: tv_audience_share, dtype: float64

Part 6: Real Biggest TV Audiences#

Ranking countries by audience shows where World Cup viewers actually are. fifa.nlargest(5, 'tv_audience_share') returns the five largest shares, keeping just the country and the value. The output is led by China at 14.8%, followed by Brazil (7.1%), Indonesia (6.7%), Japan (4.9%) and the United States (4.3%). Together these five account for 37.8% of the global audience. The table is saved as top_audience because the final summary print reuses the top country.

top_audience = fifa.nlargest(5, 'tv_audience_share')[['country', 'tv_audience_share']]
top_audience
country tv_audience_share
2 China 14.8
4 Brazil 7.1
11 Indonesia 6.7
1 Japan 4.9
0 United States 4.3

Part 7: Real Biggest Economic Weight#

The GDP-weighted share shows which audiences matter most economically, which is what sponsors and broadcasters care about. nlargest(5, 'gdp_weighted_share') ranks countries on this measure. The output is led by the United States at 11.3%, then Japan (9.1%), China (7.3%), Germany (6.3%) and Brazil (5.4%). Compared with the audience ranking, China drops from first to third and the United States rises from fifth to first, because weighting by economic output favours richer countries. Indonesia drops out of the top five entirely.

top_gdp = fifa.nlargest(5, 'gdp_weighted_share')[['country', 'gdp_weighted_share']]
top_gdp
country gdp_weighted_share
0 United States 11.3
1 Japan 9.1
2 China 7.3
3 Germany 6.3
4 Brazil 5.4

Part 8: Real Top Audience Chart#

A bar chart presents the top audiences clearly. The code takes the ten largest audience shares with nlargest(10, ...), uses set_index('country') so country names label the bars, sorts with sort_values() so the largest bar sits at the top, and draws a horizontal bar chart with kind='barh'. It is labelled and saved as top_tv_audience.png, with no displayed output because the figure is closed after saving. In the image, look at how China's bar is roughly double the length of the next one.

fig, ax = plt.subplots(figsize=(10, 6))
fifa.nlargest(10, 'tv_audience_share').set_index('country')['tv_audience_share'].sort_values().plot(kind='barh', ax=ax, color='forestgreen')
ax.set_xlabel('Real World Cup TV Audience Share, Percent')
ax.set_title('Real Top 10 Countries by World Cup TV Audience Share')
plt.tight_layout()
plt.savefig('top_tv_audience.png', dpi=100)
plt.close()

Part 9: Real Population vs Audience Gap#

Comparing audience with population reveals which countries watch more than their size would suggest. The code creates a new column, audience_vs_population, by subtracting population_share from tv_audience_share and rounding to two decimals. A positive value means a country's share of viewers is bigger than its share of the world's people. nlargest(5, ...) shows the top five: Brazil (+4.3 points), Indonesia (+3.2), Japan (+3.0), Germany (+1.7) and Mexico (+1.5). These are countries where the World Cup punches above their population weight.

fifa['audience_vs_population'] = (fifa['tv_audience_share'] - fifa['population_share']).round(2)
fifa.nlargest(5, 'audience_vs_population')[['country', 'audience_vs_population']]
country audience_vs_population
4 Brazil 4.3
11 Indonesia 3.2
1 Japan 3.0
3 Germany 1.7
12 Mexico 1.5

Part 10: Real Population-Heavy, Audience-Light Countries#

The other end of the gap column shows countries that watch less than their population would suggest. nsmallest(5, 'audience_vs_population') returns the five most negative gaps. The output is led by India at -15.6 points, then China (-4.7), Pakistan and Bangladesh (both -2.1) and the Philippines (-1.3). India's gap is by far the largest: a big share of the world's population but a small share of World Cup viewers. China appears here even though it has the largest audience, because its population share is larger still (14.8 plus 4.7, about 19.5%).

fifa.nsmallest(5, 'audience_vs_population')[['country', 'audience_vs_population']]
country audience_vs_population
38 India -15.6
2 China -4.7
74 Pakistan -2.1
113 Bangladesh -2.1
99 Philippines -1.3

Part 11: Real Average Audience by Confederation#

Comparing confederations shows which regions are most engaged on average. groupby('confederation')['tv_audience_share'].mean() averages audience share per confederation, .round(3) tidies it and sort_values(ascending=False) puts the highest first. The output shows CONMEBOL highest at 1.35%, then AFC (0.991), UEFA (0.548), CONCACAF (0.327), CAF (0.172) and OFC lowest at 0.017. Remember CONMEBOL has only 10 countries, so Brazil alone lifts its average a lot. The result is saved as confed_avg for the chart.

confed_avg = fifa.groupby('confederation')['tv_audience_share'].mean().round(3).sort_values(ascending=False)
confed_avg
confederation
CONMEBOL    1.350
AFC         0.991
UEFA        0.548
CONCACAF    0.327
CAF         0.172
OFC         0.017
Name: tv_audience_share, dtype: float64

Part 12: Real Confederation Chart#

A bar chart makes the confederation comparison easy to read. The code calls confed_avg.plot(kind='bar', ...) on the sorted averages, adds a y-axis label and title and saves the figure as confederation_audience.png. There is no displayed output because the figure is closed after saving. In the image, look for the steep drop from CONMEBOL and AFC to the rest, with OFC barely visible. Because these are averages per country, they do not show each confederation's total audience.

fig, ax = plt.subplots(figsize=(8, 6))
confed_avg.plot(kind='bar', ax=ax, color='steelblue')
ax.set_ylabel('Real Average TV Audience Share, Percent')
ax.set_title('Real Average Soccer TV Audience Share by Confederation')
plt.tight_layout()
plt.savefig('confederation_audience.png', dpi=100)
plt.close()

Part 13: Real Economic Weight Distribution#

Before correlating economic weight with audience, you should understand its shape. describe() on gdp_weighted_share shows a mean of about 0.52% but a median of 0.0%, and a maximum of 11.3%. More than half the countries round to zero on this measure. This is even more concentrated than the TV audience share, which had a median of 0.1%. A few large, wealthy audiences dominate this column, which will strongly influence any correlation you calculate.

fifa['gdp_weighted_share'].describe()
count    191.000000
mean       0.520419
std        1.457594
min        0.000000
25%        0.000000
50%        0.000000
75%        0.300000
max       11.300000
Name: gdp_weighted_share, dtype: float64

Part 14: Real GDP-to-Audience Correlation#

Now you test how closely economic weight and audience size move together. Correlation measures this on a scale from -1 to 1, where values near 1 mean a strong positive link. fifa['gdp_weighted_share'].corr(fifa['tv_audience_share']) compares the two columns, rounded to three decimals. The output is 0.771, a strong positive relationship. Keep in mind that both columns are dominated by a few big countries, so those countries drive much of this figure.

gdp_corr = round(fifa['gdp_weighted_share'].corr(fifa['tv_audience_share']), 3)
gdp_corr
np.float64(0.771)

Part 15: Real Population-to-Audience Correlation#

The same calculation for population lets you compare the two explanations. The code correlates population_share with tv_audience_share. The output is 0.731, also a strong positive relationship. It is a little lower than the GDP-weighted figure of 0.771, but only by 0.04, so both measures track audience about equally well. India, with a huge population but a small audience, is one example that pulls the population correlation down. Comparing correlations is useful, but small differences like this should not be over-interpreted.

pop_corr = round(fifa['population_share'].corr(fifa['tv_audience_share']), 3)
pop_corr
np.float64(0.731)

Part 16: Real Zero-Audience Countries#

Counting countries with no measurable audience shows how concentrated viewing is. fifa['tv_audience_share'] == 0 gives True for each country with a zero share, and .sum() counts the Trues. The output is 67, which is about 35% of the 191 countries. A zero here most likely means the share was too small to register once rounded to one decimal place, not that nobody watched. Always ask how a value of zero was produced before treating it as a true zero.

zero_audience = (fifa['tv_audience_share'] == 0).sum()
zero_audience
np.int64(67)

Part 17: Real CONCACAF Countries#

Zooming in on one confederation gives more detail than an average can. The code filters fifa to rows where confederation equals 'CONCACAF' and sorts by audience share with sort_values(..., ascending=False), then shows the top five. The output is led by the United States at 4.3% and Mexico at 3.2%, with Canada (0.5%), Cuba and Honduras (both 0.3%) far behind. Two countries hold most of the region's audience, which explains why CONCACAF's average is modest despite these large markets.

concacaf = fifa[fifa['confederation'] == 'CONCACAF'].sort_values('tv_audience_share', ascending=False)
concacaf[['country', 'tv_audience_share']].head(5)
country tv_audience_share
0 United States 4.3
12 Mexico 3.2
20 Canada 0.5
51 Cuba 0.3
85 Honduras 0.3

Part 18: Real UEFA Countries#

The same approach for Europe shows how audience is spread across UEFA. The code filters to UEFA countries, sorts by audience share and shows the top five. The output is led by Russia at 3.1%, then Germany (2.9%), Turkey (2.3%) and the United Kingdom and Italy (both 2.1%). Compared with CONCACAF, the European audience is spread much more evenly across several large countries. Filtering and sorting like this is often more informative than a single group average.

uefa = fifa[fifa['confederation'] == 'UEFA'].sort_values('tv_audience_share', ascending=False)
uefa[['country', 'tv_audience_share']].head(5)
country tv_audience_share
8 Russia 3.1
3 Germany 2.9
13 Turkey 2.3
5 United Kingdom 2.1
6 Italy 2.1

Part 19: Real Total Audience Share Check#

If tv_audience_share really is a share of a world total, it should add up to about 100 across all countries. fifa['tv_audience_share'].sum() adds every value, and round(..., 1) rounds to one decimal place. The output is 99.9, close enough to 100 to confirm the column behaves like a proper share. The small shortfall is what you would expect when each country's value has been rounded to one decimal place before being summed.

round(fifa['tv_audience_share'].sum(), 1)
np.float64(99.9)

Part 20: Real Total Population Share Check#

The same check for population confirms the second share column. round(fifa['population_share'].sum(), 1) adds all population shares. The output is 99.8, again very close to 100. The tiny gap comes from rounding the individual values, and possibly from a few territories not listed as FIFA members. If a share column summed to something far from 100, you would suspect missing countries or a column measured on a different scale.

round(fifa['population_share'].sum(), 1)
np.float64(99.8)

Part 21: Real Median Comparison#

Because the share columns are so skewed, the median gives a better picture of a typical country than the mean. Selecting the three share columns with double brackets and calling .median() returns one median per column. The output shows 0.1 for population, 0.1 for TV audience and 0.0 for GDP-weighted share. The typical FIFA member country holds roughly a tenth of a percent of the world's population and audience, and close to nothing of the economic weight.

fifa[['population_share', 'tv_audience_share', 'gdp_weighted_share']].median()
population_share      0.1
tv_audience_share     0.1
gdp_weighted_share    0.0
dtype: float64

Part 22: Real Duplicate Country Check#

Each country should appear only once, otherwise totals and rankings would be inflated. fifa['country'].duplicated() marks True for any country name already seen in an earlier row, and .sum() counts them. The output is 0, so every country is listed once. This is also why the share columns could sum to close to 100: a duplicated country would have pushed the totals above it.

fifa['country'].duplicated().sum()
np.int64(0)

Part 23: Real Gap Distribution Chart#

This chart brings both ends of the gap column together. fifa['audience_vs_population'].abs() takes the size of each gap, ignoring its sign, and sort_values(ascending=False) orders them largest first. fifa.reindex(...) reorders the table to match, and .head(10) keeps the ten biggest gaps, positive or negative. These are then sorted and drawn as a horizontal bar chart, saved as audience_gap.png, with no displayed output. In the image, look for India's long negative bar and Brazil leading the positive side.

fig, ax = plt.subplots(figsize=(10, 6))
top_gap = fifa.reindex(fifa['audience_vs_population'].abs().sort_values(ascending=False).index).head(10)
top_gap.set_index('country')['audience_vs_population'].sort_values().plot(kind='barh', ax=ax, color='darkorange')
ax.set_xlabel('Real Audience Share Minus Population Share')
ax.set_title('Real Biggest Soccer Fandom Gaps vs Population Share')
plt.tight_layout()
plt.savefig('audience_gap.png', dpi=100)
plt.close()

Part 24: Saving the Real Enriched Dataset#

Saving the dataset keeps the new audience_vs_population column so you do not have to rebuild it. fifa.to_csv('fifa_audience_enriched.csv', index=False) writes the file without the row index, which would otherwise appear as an extra unnamed column. The code reads it back and compares shapes. The output is True, so the saved file has the same rows and columns as the DataFrame, now 6 columns including the gap.

fifa.to_csv('fifa_audience_enriched.csv', index=False)
reloaded = pd.read_csv('fifa_audience_enriched.csv')
reloaded.shape == fifa.shape
True

Part 25: Real Sanity Check, Row Count#

This sanity check confirms the analysis has not added or lost rows. len(fifa) == 191 compares the current row count with the figure from the first step. The output is True. Adding a calculated column should never change the number of rows, and this confirms it did not. In a script you could wrap this in assert so the code stops if it ever fails.

len(fifa) == 191
True

Part 26: Real Sanity Check, No Missing Values#

This repeats the missing-value check as a strict True or False test, now including the new gap column. fifa.isna().sum().sum() == 0 counts every missing value and checks the total is zero. The output is np.True_, numpy's version of True, which means the same as a plain True. Re-checking after adding a calculated column is worthwhile, because a calculation involving a missing value produces another missing value.

fifa.isna().sum().sum() == 0
np.True_

Part 27: Real Sanity Check, Confederation Count#

The confederation column should contain exactly six regions. fifa['confederation'].nunique() counts the distinct values, and the code checks the count equals 6. The output is True, matching the six confederations you saw in the breakdown earlier. This check would catch problems such as a typo or inconsistent capitalisation, which would quietly create a seventh group in your averages.

fifa['confederation'].nunique() == 6
True

Part 28: Real Sanity Check, No Duplicates#

This repeats the duplicate country check as a True or False test. fifa['country'].duplicated().sum() == 0 returns True only if no country appears twice. The output is np.True_, so every country is still unique. Collecting checks like this at the end of a notebook gives you a quick list to re-run whenever the source file is updated.

fifa['country'].duplicated().sum() == 0
np.True_

Part 29: Real Top Finding Print#

Turning your main finding into a sentence makes it ready for a report. The code takes the first row of top_audience with .iloc[0], pulls out the country and its share, and builds an f-string. The output reads: China carried the largest World Cup TV audience share of any country, at 14.8 percent. Because the sentence uses stored variables, it updates automatically if the data changes.

top_country = top_audience.iloc[0]['country']
top_country_share = top_audience.iloc[0]['tv_audience_share']
print(f'{top_country} carried the real largest real World Cup TV audience share of any country, at {top_country_share} percent.')
China carried the real largest real World Cup TV audience share of any country, at 14.8 percent.

Part 30: Real Recap Print#

The final print summarises the comparison between the two explanations for audience size. It uses len(fifa) and the stored gdp_corr and pop_corr inside an f-string. The output states that across 191 FIFA member countries, GDP-weighted share correlated with TV audience share at 0.771, versus 0.731 for population share. Both are strong, and the gap between them is small. Building summaries from variables keeps them consistent with the analysis.

print(f'Across {len(fifa)} real FIFA member countries, GDP-weighted share correlated with TV audience share at {gdp_corr}, versus {pop_corr} for real raw population share.')
Across 191 real FIFA member countries, GDP-weighted share correlated with TV audience share at 0.771, versus 0.731 for real raw population share.

Wrap-Up: What You Learned#

  • This real dataset covers one hundred ninety-one real FIFA member countries, with genuinely zero missing values and genuinely zero duplicates.
  • Real economic weight tracked real TV audience share far more tightly than real raw population size did in this dataset, a real concrete finding about who actually drives soccer's global reach.
  • Real audience share and real population share each summed to approximately one hundred percent, confirming these are genuinely valid real share measures.
  • This real domain has now covered five genuinely different sports contexts, basketball, tennis, baseball, football, and soccer, using five real independently sourced datasets.
  • Every real number in this lesson traces back to genuinely real, complete FiveThirtyEight data, the same honest-sourcing standard carried through every domain so far.
  • Next video: a real FIDE chess federation transfer dataset, continuing this domain with a sixth completely different competitive activity.

Practice on your own

  • Group by confederation and take the .sum() of tv_audience_share instead of the mean, then compare which region holds the largest total audience.
  • Create a second gap column, gdp_weighted_share minus tv_audience_share, and list the five countries where economic weight most exceeds audience share.
  • Repeat the two correlations after removing China and India with ~fifa['country'].isin(['China', 'India']) and see how much each figure changes.

One note on the bullets above: GDP-weighted share (0.771) tracked audience only slightly more closely than population (0.731), so treat the difference as modest. The next video in the series looks at a FIDE chess federation transfer dataset.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.