[I'll soon be starting the sixth cohort of my four-month, online Python Data Analytics Bootcamp. This is the best (and most intensive) course that I offer, giving you a chance to level up your Python and Pandas knowledge with frequent meetings, interactions, and collaboration. Learn more at https://PythonDAB.com, or join me at a free webinar I'm giving one hour from now: https://store.lerner.co.il/pythondab-6-info-webinar-1 . ]
This week, we took a (hopefully) somewhat amusing detour from the serious news that has been surrounding us over the last few weeks. We looked at roller coasters — where they are located, and what they're made out of. I hope that any screaming you did while trying to solve these problems was because you identified with the amusement-park rides, rather than out of frustration with trying to solve the problems.
Data and six questions
This week's data comes from RCDB, the Roller Coaster Database, at https://rcdb.com . RCDB has a very extensive database of roller-coaster information. However, it's not downloadable directly; instead, you need to scrape the page, and ask Pandas to turn it into a data frame. Along the same lines, we used (in one question) the Wikipedia page for the G20 countries, at https://en.wikipedia.org/wiki/G20.
Below are my solutions and explanations for these six questions. As always, a link to the Jupyter notebook I used to solve them at the bottom of this post.
The "Locations" page at RCDB, https://rcdb.com/location.htm, lists every country and territory, and the number of roller coasters that it has. Create a Pandas data frame from the table on this page. Make the "Location" column the index, and make the "Roller Coasters" column an integer value, treating missing values as 0.
The first thing we'll have to do is load Pandas:
import pandas as pdWith that in place, we can now import the location list from RCDB into a Pandas data frame, using read_html. This top-level (pd) method goes to a URL and returns each of the HTML tables it finds there as a Pandas data frame. It's sometimes surprising to find just how many tables there are on a page; HTML tables are sometimes used for layout purposes, not just to organize data into rows and tables.
I set the URL, and then used read_html to retrieve a list of data frames. After a quick examination, I found that the second data frame was the one that I wanted. I thus retrieved index [1] from the list that we got back:
url = 'https://rcdb.com/location.htm'
df = (pd
.read_html(url)[1]
)
The result is indeed a data frame with a Location column – the column that I asked you to make into its index. We can do that by invoking set_index on the data frame:
url = 'https://rcdb.com/location.htm'
df = (pd
.read_html(url)[1]
.set_index('Location')
)
I then asked you to make some changes on the Roller Coasters column, which indicates how many roller coasters are in a given country. By default, the column has a dtype of object, which means that Pandas couldn't interpret the values as either integers or floats, and thus treated them as strings. This is because RCDB's missing values are indicated with '-'.
In order to set the dtype to be int, we'll need to do three things:
- Replace the
'-'values withNaN - Replace
NaNvalues with 0 - Set the
dtypeto beint
I did this first by passing the na_values keyword argument to read_html, indicating that '-' should be treated as NaN. I then used assign to create a new column, roller_coasters. That column is the result of invoking fillna(0) (turning NaN values into 0) and then astype(int) , getting back an integer series.
Notice that because of Python's syntax, and the fact that assign uses keyword arguments to name the column to which we want to assign, I had to rename to the column to roller_coasters:
url = 'https://rcdb.com/location.htm'
df = (pd
.read_html(url, na_values='-')[1]
.set_index('Location')
.assign(roller_coasters=lambda df_: df_['Roller Coasters'].fillna(0).astype(int))
)
We now have two columns indicating how many roller coasters are in each country, one containing integers (roller_coasters) and one containing strings (Roller Coasters). I decided to remove the latter column with drop.
In the past, I've named the columns I wanted to remove, and then passed the keyword argument axis='columns'. But I've recently learned that there's a cleaner and nicer way to do this, just passing the keyword argument columns, and giving it the list of columns we want to remove:
url = 'https://rcdb.com/location.htm'
df = (pd
.read_html(url, na_values='-')[1]
.set_index('Location')
.assign(roller_coasters=lambda df_: df_['Roller Coasters'].fillna(0).astype(int))
.drop(columns=['Roller Coasters'])
)
The result is a 177-row, 6-column data frame.
Three country names came out garbled, with non-alphabetical characters. Which ones? How can we resolve this?
read_html works quite well. But it's not infallible, and I noticed when reviewing the results that three country names contained weird characters. How can we identify these countries?
I decided to use regular expressions, a powerful tool for describing patterns of text. (If you don't know regular expressions, you can learn them via my free Regular Expressions Crash Course, at https://regexpcrashcourse.com/.)
My logic was as follows:
- Go through each element in the index (
df.index), and check if it contains only characters that we would want/expect to be in country names. The regular expression will be^[- \w\']+$, which means:- Must match from the start (
^) - We then have a character class, meaning that we want a character from the set that we define. The set here includes
-(minus),' '(space), and\w(any letter, digit, or_, including characters from non-Latin character sets) - We want one or more elements from the character class (
+) - We want to anchor the regexp to the end of the string (
$)
- Must match from the start (
- If the country name does not match that expectation, then we want to keep it
- I put this in a list comprehension, iterating over every element in
df.index - The result was a Python list, which I then put through
sortedto get the country names in alphabetical order.
In the end, the code looks like this:
import re
sorted([one_name
for one_name in df.index
if not re.search(r'^[- \w\']+$', one_name) ])This worked just fine, and gave me the following results:
['Curaçao', "Côte d'Ivoire", 'São Tomé and PrÃ\xadncipe']As we can see, these names contain some weird characters. But why these characters? What makes them so weird?
The answer, in a word, is "encoding." Computers use bytes to store information, and if you're using English, then one byte is the same as one character. But in order to handle other languages and character sets, we often need to use more than one byte per character. How we translate several bytes into a character is a question that has multiple answers, each known as an "encoding."
The most common encoding used in modern Python is UTF-8, which gives us access to the full Unicode character set – allowing us to use nearly any character from most languages, as well as emojis and similar signals. UTF-8 uses a single byte for characters that existed in ASCII, but two, three, or more bytes for other characters. That's why we're seeing two funny characters in these countries' names where there should be a single one. Those funny characters aren't legitimate UTF-8 characters, so they show up, not matching the \w builtin character class in our regular expression.
The simplest solution to this problem is to return to our call to read_html, telling it that we want to interpret the bytes we downloaded from the Web site in UTF-8. We can do that by passing encoding='utf-8' as a keyword argument:
df = (pd
.read_html(url, na_values='-', encoding='utf-8')[1]
.set_index('Location')
.assign(roller_coasters=
lambda df_: df_['Roller Coasters'].fillna(0).astype(int))
.drop(columns=['Roller Coasters'])
)Sure enough, this does the trick! If I re-run my list comprehension, I get an empty list – meaning that all of the characters in all of the country names are now legitimate.
Which five G20 countries (as listed at https://en.wikipedia.org/wiki/G20) have the most roller coasters, and who are the leaders of these countries? If a country appears more than once (because the list includes both the head of state and head of government), then show only the first one to appear. Remove any numeric footnotes.
In order to solve this, we'll first need to create a data frame from the G20 countries, again using read_html. It turns out that the G20 table on that Wikipedia page is at index 2. We read it into memory, and immediately use set_index to make the country name the index – so that we can more easily merge it with the existing df later on:
g20_url = 'https://en.wikipedia.org/wiki/G20'
g20_df = pd.read_html(g20_url)[2].set_index('Member')We could get the head of each country's government by retrieving the Leader column from g20_df. But we don't want all of the government leaders. Rather, we just want those from the five countries with the most roller coasters. In order to do that, we'll need to join the two data frames together. join uses the index from one data frame, and finds matching index values on the second data frame. It then produces one new data frame with all of the matches; each row in the resulting data frame has the combined set of columns from both data frames.
We can join them together as follows, using sort_values to sort by the number of roller coasters in each country, from greatest to smallest:
(
g20_df
.join(df)
.sort_values('roller_coasters', ascending=False)
)In theory, I could use head(5) to retrieve only the five first rows from the combined data frame. That would give me the five countries with the most roller coasters, right? Well, not exactly – it turns out that the G20 table we downloaded from Wikipedia lists both the head of state and the head of government for some countries. The way that the HTML table was turned into a data frame means that we have two rows in our data frame for some countries, such as China.
How can we cut that down? I decided to use .loc along with lambda, as I often do. But the lambda expression (i.e., an anonymous function) will get a True or False value based on whether the index is a duplicated value. That is, Pandas will go through each value in df.index and tell us whether it's duplicated (True) or not (False). We can then keep only those that aren't duplicated.
But wait: We want the duplicated values! We just want each of them once! Fine, so we'll pass keep='first' to index.duplicated. Then we'll use ~, which reverses the boolean value in an expression. The result will be a boolean series in which True indicates that it's a unique index value, or the first of several non-unique values. Applying that to the data frame via loc means that we'll get only unique or first-of-non-unique values. We can then retrieve the first five rows with head(5):
(
g20_df
.join(df)
.sort_values('roller_coasters', ascending=False)
.loc[lambda df_: ~df_.index.duplicated(keep='first')]
.head(5)
)Finally, since we want the leaders, we can use [] to retrieve that column. To remove the footnotes – numbers inside of [] in the text – I used str.replace with a regular expression, turning square brackets with digits inside of them into an empty string:
(
g20_df
.join(df)
.sort_values('roller_coasters', ascending=False)
.loc[lambda df_: ~df_.index.duplicated(keep='first')]
.head(5)
['Leader']
.str.replace(r'\[\d+\]', '', regex=True)
)The result:
Member
China Xi Jinping
United States Donald Trump
Germany Olaf Scholz
France Emmanuel Macron
Japan Shigeru Ishiba
Name: Leader, dtype: objectBut ... wait a second! I'm writing this on November 7th, two days after the US had its presidential election. Donald Trump won the election, but he isn't yet president. True, but Wikipedia is edited by a large number of volunteers, and it seems that either one of them jumped the gun or (if I understood the editing discussion correctly) because Trump is the president-elect, he is given an invitation to the G20 – whose summit will take place once he's in office.
Now create a data frame from data for the United States, at https://rcdb.com/location.htm?id=59 . Which US states/territories lack any roller coasters at all? What's the total number of people who live in such places?
Next, I asked you to calculate the number of people who live in US states and territories that lack roller coasters. We'll start with the same series of method calls as before, downloading the URL, replacing NaN values with 0, and removing the original Roller Coasters column:
url = 'https://rcdb.com/location.htm?id=59'
(
pd
.read_html(url, na_values='-')[1]
.set_index('Location')
.assign(roller_coasters=lambda df_:
df_['Roller Coasters'].fillna(0).astype(int))
.drop(columns=['Roller Coasters'])
)We can use loc and lambda to find those locations that have a roller_coasters value of 0. Then we can retrieve the Population column:
url = 'https://rcdb.com/location.htm?id=59'
(
pd
.read_html(url, na_values='-')[1]
.set_index('Location')
.assign(roller_coasters=lambda df_:
df_['Roller Coasters'].fillna(0).astype(int))
.drop(columns=['Roller Coasters'])
.loc[lambda df_: df_['roller_coasters'] == 0]
['Population']
)The result:
Location
Washington, D.C. 702455
Rhode Island 1057315
Puerto Rico 3195153
Delaware 967171
Hawaii 1420491
Name: Population, dtype: int64We can total that by invoking sum on the resulting series:
url = 'https://rcdb.com/location.htm?id=59'
(
pd
.read_html(url, na_values='-')[1]
.set_index('Location')
.assign(roller_coasters=lambda df_:
df_['Roller Coasters'].fillna(0).astype(int))
.drop(columns=['Roller Coasters'])
.loc[lambda df_: df_['roller_coasters'] == 0]
['Population']
.sum()
)I get a result of np.int64(7342585), aka 7,342,585.
California has 97 working roller coasters. Information about its roller coasters are spread across five pages, with the URL pattern https://rcdb.com/r.htm?page=n&ot=2&ol=1499&ex (and "n" varies from 1 to 5). Create a single data frame from these five pages, dropping the first (unnamed) column and the "opened" column.
To get all of the California roller coasters into a single data frame, we'll need to iterate over each page of the URL pattern I gave. We could iterate with a regular for loop, but to me this seems like a great chance to use a list comprehension. The comprehension will return a list of data frames, which we can then combine together.
Here's the query that I came up with:
[pd
.read_html(
f'https://rcdb.com/r.htm?page={page_number}&ot=2&ol=1499&ex')
[1]
for page_number in range(1, 6)]
The above retrieves the five pages (numbered 1-5) on the RCDB site, grabbing one page at a time. Notice that we have to retrieve index [1] from the list we get from read_html, since the page contains other tables, too.
Now that we have our list of data frames, what can we do with them? I decided to pass it along to pd.concat, which combines a number of data frames and returns a new one. By default, it stacks them on top of one another, so the column names need to match up. (In this case, they definitely do.) Here's the query:
df = (
pd.concat(
[pd
.read_html(
f'https://rcdb.com/r.htm?page={page_number}&ot=2&ol=1499&ex')
[1]
for page_number in range(1, 6)])
.drop(columns=['Unnamed: 0', 'Opened'])
)
We end up with a data frame containing 97 rows and 5 columns.
From those California roller coasters, create a table showing how many working ones are of each type (wood or steel), and how many are of each design.
Finally, I asked you to create a table listing type (wood or steel) vs. the design. This means taking two categorical columns from the California data, turning one category into an index and the other category into column names. The values would then be the number of times that row-column combination appeared in the California data.
First, we're only interested in operating roller coasters. So we'll have to filter those out:
(
df
.loc[lambda df_: df_['Status'] == 'Operating']
)With that out of the way, we need to count. This task sounds familiar, too: With two categorical columns and an aggregation method (count), we could use a pivot table, invoked via pivot_table:
(
df
.loc[lambda df_: df_['Status'] == 'Operating']
.pivot_table(index='Type',
columns='Design',
values='Roller Coaster',
aggfunc='count')
)And indeed, that works:
Design Flying Inverted Sit Down Stand Up Suspended Wing
Type
Steel 1.0 5.0 74.0 1.0 1.0 2.0
Wood NaN NaN 6.0 NaN NaN NaNBut another way to do this is with the pd.crosstab function. We pass two series, and it shows how often they match up. In other words, we could say:
pd.crosstab(df['Type'], df['Design'])But this won't work, because pd.crosstab is a top-level Pandas method. And we want to invoke it on the data frame we got back via method chaining. How can we do that?
The answer is pipe, a method for data frames that lets us invoke a top-level function. Instead of df.METHOD(ARG1, ARG2), we call df.pipe(FUNCTION, ARG1, ARG2). In other words, we pass the function as an argument to df.pipe, thus preserving the method chain. Here's how that would look:
(
df
.loc[lambda df_: df_['Status'] == 'Operating']
.pipe(lambda df_: pd.crosstab(df_['Type'], df_['Design']))
)And indeed, it works great, giving us the following output:
Design Flying Inverted Sit Down Stand Up Suspended Wing
Type
Steel 1 5 74 1 1 2
Wood 0 0 6 0 0 0As you can see, the output is almost identical. The difference, however, is that crosstab gives us zeroes when there is no data, because it's just trying to count. By contrast. pivot_table gives us NaN values when it doesn't have any data. And because there are NaN values, the columns need to be of type float, since NaN is a float.
And there we go! I hope that you enjoyed this topic.
And of course, here's a link to my Jupyter notebook: https://drive.google.com/file/d/1zw8Gxdqn59542qqaD0sS6miPtwoQP51r/view?usp=sharing
I'll be back on Wednesday with more Pandas puzzles based on current events.
Reuven