Mathew K Analytics

Lesson 49 · Real-World Data Analytics

Split Text into Columns & crosstab: Rio 2016 Olympics Data | Python Data Analytics #49

Moving to a genuinely multi-sport dataset for the first time in this domain. A real dataset of three hundred six real events held at the 2016 Rio Olympics,…

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 49: Real Rio 2016 Olympics Events Analysis#

  • Video forty-nine of the hundred-video real-world data analytics series, moving to a genuinely multi-sport dataset for the first time in this domain.
  • A real dataset of three hundred six real events held at the 2016 Rio Olympics, across twenty-eight real sports, sourced from a real independent GitHub repository rather than FiveThirtyEight.
  • Let's get into it.

This lesson is for learners who can summarise a table with value_counts() and want practice with categorical data, text columns that hold several values, and grouping categories into custom buckets. The question is how the 2016 Rio Olympics schedule was built: which sports had the most medal events, how events were split between men, women and mixed competition, and which venues did the most work. The dataset lists 306 events across 28 sports and comes from an independent GitHub repository rather than FiveThirtyEight. The columns that matter are sport, discipline (a subdivision such as backstroke or track), name (the event title), sex and venues.

In this lesson you will:

  • count and rank categories, including finding ties for the smallest
  • split a comma-separated text column into separate values with str.split and explode
  • use isin to group sports into your own categories
  • build a new category column with nested np.where

Prerequisites: you should be comfortable with boolean filtering and value_counts(). Earlier lessons in the series cover these if you need a refresher.

Part 1: A Real Rio 2016 Events Dataset#

Confirming the size of the data first gives you a reference point for every later count. The code imports pandas, numpy and matplotlib, reads rio2016_events.csv into a DataFrame called events and checks .shape. The output is (306, 6): 306 events described by six columns. That matches the 306 events stated in the lesson introduction. Because each row is one event, any count of rows is a count of events, which keeps the rest of the analysis simple.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
events = pd.read_csv('rio2016_events.csv')
events.shape
(306, 6)

Part 2: Real Data Preview#

Seeing real rows shows how each column is written, which matters for filtering later. The code lists the columns and then shows head(5); only the last result is displayed. The first rows are swimming events, with sport set to 'aquatics', discipline to values such as 'backstroke', a readable name such as 'Women's 100m Backstroke', sex as 'female' or 'male', and venues as 'Olympic Aquatics Stadium'. Notice that sport and sex values are in lower case, so filters must match that exactly.

events.columns.tolist()
events.head(5)
id sport discipline name sex venues
0 701492 aquatics backstroke Women's 100m Backstroke female Olympic Aquatics Stadium
1 305278 aquatics backstroke Women's 200m Backstroke female Olympic Aquatics Stadium
2 708010 aquatics backstroke Men's 100m Backstroke male Olympic Aquatics Stadium
3 729643 aquatics backstroke Men's 200m Backstroke male Olympic Aquatics Stadium
4 567019 aquatics breaststroke Women's 100m Breaststroke female Olympic Aquatics Stadium

Part 3: Real Missing Data Check#

Missing values would make some events disappear from counts without warning. isna().sum() counts empty cells in each column. The output shows zero missing values in all six columns, so every event has a sport, discipline, name, sex category and venue. That means you can count and group without needing to decide how to handle gaps, which is not something you can take for granted with real data.

events.isna().sum()
id            0
sport         0
discipline    0
name          0
sex           0
venues        0
dtype: int64

Part 4: Real Duplicate Row Check#

Duplicate rows would make some sports look bigger than they are. duplicated() marks a row True when it exactly repeats an earlier row, and .sum() counts them. The output is 0, so no event is listed twice. Because each row also has its own id, a full-row duplicate would be unlikely anyway. If you wanted a stricter test, you could check for repeated event names within a sport using duplicated(subset=['sport', 'name']).

events.duplicated().sum()
np.int64(0)

Part 5: Real Sport Count#

Knowing how many categories a column holds helps you choose how to present it. nunique() counts the distinct values in sport, and the output is 28. That is too many for a readable pie chart or a single crowded bar chart, which is why later steps focus on the top ten and on grouped categories. It also matches the 28 sports stated in the lesson introduction.

events['sport'].nunique()
28

Part 6: Real Events per Sport#

Ranking sports by number of events shows where the medal opportunities were concentrated. value_counts() counts events per sport and sorts from most to least, and .head(10) displays the top ten. Athletics leads with 47 events, closely followed by aquatics with 46. There is then a big drop to cycling, gymnastics and wrestling, each with 18. Just two sports account for 93 of the 306 events. The full counts are stored in events_per_sport, which several later steps reuse.

events_per_sport = events['sport'].value_counts()
events_per_sport.head(10)
sport
athletics        47
aquatics         46
cycling          18
gymnastics       18
wrestling        18
canoe            16
weightlifting    15
shooting         15
judo             14
rowing           14
Name: count, dtype: int64

Part 7: Real Top Sports Chart#

A bar chart makes the gap between the two leading sports and the rest very clear. The code plots the top ten counts as horizontal bars and uses ax.invert_yaxis() so the largest sport, athletics, appears at the top instead of the bottom. The chart is saved to top_sports.png and closed, so it does not show in the notebook. When you open it, look for the two long bars at the top and the much shorter, similar-length bars below them.

fig, ax = plt.subplots(figsize=(9, 6))
events_per_sport.head(10).plot(kind='barh', ax=ax, color='seagreen')
ax.invert_yaxis()
ax.set_xlabel('Real Number of Events')
ax.set_title('Real Ten Rio 2016 Sports with the Most Events')
plt.tight_layout()
plt.savefig('top_sports.png', dpi=100)
plt.close()

Part 8: Real Discipline Count#

Disciplines sit one level below sports, so counting them shows how much variety exists inside each sport. nunique() on discipline returns 50. With 28 sports, many sports must have only one discipline while a few, such as aquatics and athletics, split into several. Comparing the two counts like this is a quick way to understand how a category hierarchy is structured before you drill into it.

events['discipline'].nunique()
50

Part 9: Real Athletics Discipline Breakdown#

Athletics is the biggest sport, so it is worth seeing what it is made of. The code filters to rows where sport equals 'athletics', selects the discipline column and counts values. Track events dominate with 24 of the 47, followed by throws and jumps with 8 each, road events with 5 and combined events (the heptathlon and decathlon) with 2. Filtering first and then counting is a pattern you can reuse to break down any sport.

athletics_breakdown = events[events['sport'] == 'athletics']['discipline'].value_counts()
athletics_breakdown
discipline
track       24
throws       8
jumps        8
road         5
combined     2
Name: count, dtype: int64

Part 10: Real Sex Category Breakdown#

Splitting events by sex category is a simple way to look at balance in the schedule. value_counts() on sex counts each category. The output shows 161 men's events, 136 women's events and just 9 mixed events. The three add up to 306, so every event falls into exactly one category. The gap between men's and women's events is measured precisely in a later step.

sex_counts = events['sex'].value_counts()
sex_counts
sex
male      161
female    136
mixed       9
Name: count, dtype: int64

Part 11: Real Sex Breakdown Chart#

A small bar chart presents the three sex categories at a glance. The code plots sex_counts as vertical bars, passing a list of three colours so each bar gets its own. plt.xticks(rotation=0) keeps the category labels horizontal so they are easy to read. The chart is saved to sex_breakdown.png and closed, so it does not display in the notebook. Look for the two tall bars for male and female and the very short bar for mixed.

fig, ax = plt.subplots(figsize=(7, 6))
sex_counts.plot(kind='bar', ax=ax, color=['steelblue', 'firebrick', 'darkorange'])
ax.set_ylabel('Real Number of Events')
ax.set_title('Real Rio 2016 Events by Sex Category')
plt.xticks(rotation=0)
plt.tight_layout()
plt.savefig('sex_breakdown.png', dpi=100)
plt.close()

Part 12: Real Mixed-Sex Events#

With only nine mixed events, it is practical to list them all. The code filters rows where sex equals 'mixed' and keeps the sport, discipline and name columns. The output shows mixed doubles in badminton and tennis, the Nacra 17 mixed sailing class and six equestrian events across dressage, eventing and jumping. Equestrian accounts for six of the nine, because men and women compete against each other in that sport.

mixed_events = events[events['sex'] == 'mixed'][['sport', 'discipline', 'name']]
mixed_events
sport discipline name
101 badminton badminton Mixed Doubles
151 equestrian dressage Dressage Individual
152 equestrian dressage Dressage Team
153 equestrian eventing Eventing Individual
154 equestrian eventing Eventing Team
155 equestrian jumping Jumping Individual
156 equestrian jumping Jumping Team
234 sailing sailing Nacra 17 Mixed
266 tennis tennis Mixed Doubles

Part 13: Real Venue Extraction#

The venues column sometimes lists several venues in one cell, separated by commas, so you cannot count venues directly. str.split(', ') turns each cell into a list of venue names, and explode() gives each list item its own row, so one event at three venues becomes three rows. nunique() then counts distinct venues, and the output is 37. Splitting on ', ' with the space matters: splitting on ',' alone would leave leading spaces and create false duplicates.

all_venues = events['venues'].str.split(', ').explode()
all_venues.nunique()
37

Part 14: Real Busiest Venues#

Ranking venues shows which sites carried the heaviest event load. Because all_venues has one row per event and venue pair, value_counts() counts how many events each venue hosted. The Olympic Stadium leads with 44, then the Olympic Aquatics Stadium with 34, Carioca Arena 2 with 32, Lagoa Stadium with 26 and Rio Olympic Arena with 18. An event held across several venues is counted once at each, so these totals can add up to more than 306.

busiest_venues = all_venues.value_counts().head(5)
busiest_venues
venues
Olympic Stadium             44
Olympic Aquatics Stadium    34
Carioca Arena 2             32
Lagoa Stadium               26
Rio Olympic Arena           18
Name: count, dtype: int64

Part 15: Real Busiest Venues Chart#

A chart of the five busiest venues makes the ranking easy to share. The code plots busiest_venues as horizontal bars and uses ax.invert_yaxis() so the Olympic Stadium appears at the top. It is saved to busiest_venues.png and closed, so nothing displays in the notebook. When you open it, look at how close the second and third venues are, at 34 and 32 events.

fig, ax = plt.subplots(figsize=(9, 6))
busiest_venues.plot(kind='barh', ax=ax, color='purple')
ax.invert_yaxis()
ax.set_xlabel('Real Number of Events Hosted')
ax.set_title('Real Busiest Venues at the 2016 Rio Olympics')
plt.tight_layout()
plt.savefig('busiest_venues.png', dpi=100)
plt.close()

Part 16: Real Multi-Venue Events#

It is useful to know which events were spread across several venues, because they behave differently from single-site events. str.contains(',') returns True for any venue cell that includes a comma, and the filter keeps those rows. The output shows seven such events: the men's and women's aquatics events named simply 'Men' and 'Women', women's basketball, the men's and women's football tournaments, and both modern pentathlon events. The long venue lists are cut off with '...' in the display; use pd.set_option('display.max_colwidth', None) to see them in full.

multi_venue = events[events['venues'].str.contains(',')][['sport', 'name', 'venues']]
multi_venue
sport name venues
44 aquatics Women Maria Lenk Aquatics Centre, Olympic Aquatics S...
45 aquatics Men Maria Lenk Aquatics Centre, Olympic Aquatics S...
102 basketball Women Carioca Arena 1, Youth Arena
167 football Women Mineirão, Olympic Stadium, Fonte Nova Arena, A...
168 football Men Mineirão, Olympic Stadium, Fonte Nova Arena, A...
207 modern pentathlon Women's Individual Deodoro Aquatics Centre, Deodoro Stadium, Yout...
208 modern pentathlon Men's Individual Deodoro Aquatics Centre, Deodoro Stadium, Yout...

Part 17: Real Combat Sports Total#

Grouping sports into broader categories lets you answer questions the raw sport list cannot. The code defines a list of five combat sports: judo, boxing, wrestling, taekwondo and fencing. isin(combat_sports) returns True for each event whose sport is in that list, and .sum() counts them. The output is 63 combat events. The list is your own definition, so state it clearly whenever you quote the number, since someone else might include or exclude different sports.

combat_sports = ['judo', 'boxing', 'wrestling', 'taekwondo', 'fencing']
combat_total = events['sport'].isin(combat_sports).sum()
combat_total
np.int64(63)

Part 18: Real Water Sports Total#

The same isin approach measures water sports. The list contains aquatics, canoe, rowing, sailing and triathlon, and the output is 88 events. Including triathlon is a judgement call, since it also involves cycling and running. This is a good example of how category definitions shape results: moving one sport in or out changes the total. Write your list down so others can reproduce it.

water_sports = ['aquatics', 'canoe', 'rowing', 'sailing', 'triathlon']
water_total = events['sport'].isin(water_sports).sum()
water_total
np.int64(88)

Part 19: Real Smallest Sports by Event Count#

The smallest sports are as interesting as the largest, but there may be several tied at the bottom. The code compares events_per_sport with its own minimum and keeps every sport that matches, rather than using .tail(1), which would return only one. The output shows eight sports tied with just 2 events each: golf, football, basketball, hockey, rugby sevens, modern pentathlon, handball and triathlon. Most of these are team sports with one men's and one women's tournament.

smallest_sports = events_per_sport[events_per_sport == events_per_sport.min()]
smallest_sports
sport
golf                 2
football             2
basketball           2
hockey               2
rugby sevens         2
modern pentathlon    2
handball             2
triathlon            2
Name: count, dtype: int64

Part 20: Real Average and Median Events per Sport#

Comparing the mean and median tells you whether a few large sports distort the picture. The mean number of events per sport is 10.9, while the median, the middle value, is 7.0. The mean is much higher because athletics and aquatics, with 47 and 46 events, pull it up. When a distribution is skewed like this, the median is usually the better description of a typical sport.

mean_events = round(events_per_sport.mean(), 1)
median_events = events_per_sport.median()
mean_events, median_events
(np.float64(10.9), np.float64(7.0))

Part 21: Real Male vs Female Event Gap#

Expressing the gap as a single number makes the earlier counts easier to talk about. The code counts men's and women's events with boolean masks and .sum(), then subtracts one from the other. Only the final subtraction is displayed, and the output is 25: there were 25 more men's events than women's events at Rio 2016. This matches the earlier breakdown of 161 and 136.

male_events = (events['sex'] == 'male').sum()
female_events = (events['sex'] == 'female').sum()
male_events - female_events
np.int64(25)

Part 22: Real Mixed-Event Share#

A share often communicates better than a raw count. Comparing sex with 'mixed' gives a True or False for each event, and .mean() on that boolean gives the proportion that are True. Multiplying by 100 and rounding gives a percentage. The output is 2.9, so fewer than 3% of events were mixed. This boolean-mean pattern is one of the most useful shortcuts in pandas for calculating shares.

mixed_share = round((events['sex'] == 'mixed').mean() * 100, 1)
mixed_share
np.float64(2.9)

Part 23: Real Sport Category Flag Column#

Storing the category as a column means you can group and count by it like any other field. np.where works like an if-else for every row: if the sport is in the combat list, the value is 'combat'; otherwise a second, nested np.where checks the water list and returns 'water' or 'other'. The output shows 155 other events, 88 water and 63 combat, matching the earlier totals. Because the combat check runs first, a sport in both lists would be labelled combat, which is worth knowing if you edit the lists.

events['category'] = np.where(events['sport'].isin(combat_sports), 'combat', np.where(events['sport'].isin(water_sports), 'water', 'other'))
events['category'].value_counts()
category
other     155
water      88
combat     63
Name: count, dtype: int64

Part 24: Real Category Share#

Shares make the category split easy to compare with other Games or datasets. value_counts(normalize=True) returns proportions instead of counts, and the code multiplies by 100 and rounds. The output shows other sports at 50.7%, water sports at 28.8% and combat sports at 20.6%. Together, the two groups you defined cover almost half of all events. The shares add up to slightly more than 100 only because of rounding.

category_share = round(events['category'].value_counts(normalize=True) * 100, 1)
category_share
category
other     50.7
water     28.8
combat    20.6
Name: proportion, dtype: float64

Part 25: Saving the Real Enriched Dataset#

Saving the data keeps the new category column for future work. to_csv writes events to rio2016_events_enriched.csv with index=False, which stops pandas saving the row index as an extra column. The code reloads the file and compares shapes, and the output True confirms the round trip worked. Note that the exploded venue list was kept in a separate variable, so the saved file still has one row per event.

events.to_csv('rio2016_events_enriched.csv', index=False)
reloaded = pd.read_csv('rio2016_events_enriched.csv')
reloaded.shape == events.shape
True

Part 26: Real Sanity Check, Total Events#

A row count check confirms that nothing during the analysis added or removed events. The code compares len(events) with 306, and the output True shows the table is unchanged in size. The explode step could have multiplied rows if it had been applied to events itself, which is exactly the kind of accident this check would catch.

len(events) == 306
True

Part 27: Real Sanity Check, Sport Count#

This check confirms the number of sports has not changed. nunique() on sport is compared with 28, and the output True shows it still matches. Simple checks like this are cheap and make your notebook self-testing: if the source file is ever updated or edited, a failing check tells you straight away which assumption no longer holds.

events['sport'].nunique() == 28
True

Part 28: Real Sanity Check, Category Totals#

The last sanity check confirms every event received exactly one category. Summing the counts from value_counts() on category and comparing with 306 returns np.True_. Because np.where always returns one of its options, no event can be left blank, but this check also proves no rows were lost. It gives you confidence that the shares calculated earlier cover the full schedule.

events['category'].value_counts().sum() == 306
np.True_

Part 29: Real Top Finding Print#

A clear sentence is the easiest way to share a finding. The code takes the first sport from events_per_sport with .index[0] and its count with .iloc[0], then uses .title() to capitalise the name. The printed output reads that athletics led all Rio 2016 sports with 47 events. Because value_counts() already sorted the counts, the first entry is guaranteed to be the largest.

top_sport = events_per_sport.index[0]
top_sport_count = events_per_sport.iloc[0]
print(f'{top_sport.title()} led all real Rio 2016 sports with {top_sport_count} real individual events.')
Athletics led all real Rio 2016 sports with 47 real individual events.

Part 30: Real Recap Print#

The recap brings the main numbers together for a reader who will not read the code. The f-string combines the event, sport and venue counts with the combat and water totals and the mixed share. The printed output says that across 306 events in 28 sports and 37 venues, 63 were combat-sport events, 88 were water-sport events and only 2.9% were mixed. If you share this, include your definitions of combat and water sports alongside it.

print(f'Across {len(events)} real Rio 2016 events spanning {events["sport"].nunique()} real sports and {all_venues.nunique()} real venues, {combat_total} were combat-sport events, {water_total} were water-sport events, and only {mixed_share} percent were open to mixed competition.')
Across 306 real Rio 2016 events spanning 28 real sports and 37 real venues, 63 were combat-sport events, 88 were water-sport events, and only 2.9 percent were open to mixed competition.

Wrap-Up: What You Learned#

  • This real lesson used a real Rio 2016 Olympics events dataset from an independent GitHub source, not FiveThirtyEight, honestly citing that different real origin.
  • Athletics and aquatics were the real two biggest sports by event count, together accounting for a real large share of every event at the Games.
  • Real men's events outnumbered real women's events, and real mixed-sex events remained a genuinely small share of the real full schedule.
  • This real domain has now covered nine genuinely different competitive contexts, basketball, tennis, baseball twice, football twice, soccer, chess, and now a real multi-sport Olympic dataset, using nine real independently sourced datasets.
  • Next video: the real Domain 5 capstone, pulling together a real one-line summary from every real sports dataset built across this entire domain.

Practice on your own

  1. Build a table of men's, women's and mixed events for each sport with pd.crosstab(events['sport'], events['sex']) and find the sports where men's and women's event counts differ.
  2. Repeat the athletics discipline breakdown for aquatics, then chart both breakdowns side by side.
  3. Using the exploded venue list, count how many different sports each venue hosted. You will need to explode a DataFrame that keeps both sport and the split venues column.

The next lesson is the Domain 5 capstone, which pulls together a one-line summary from every sports dataset built across this domain. Watch the video walkthrough of this lesson if any step felt unclear.

Found this useful?

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