Skip to content
15 min read datetime multi-index plotting sorting web-scraping

Bamboo Weekly #90: Voter participation (solutions)

Get better at: Date formats, multi-indexes, plotting, sorting, and scraping

Bamboo Weekly #90: Voter participation (solutions)

US elections are less than one week from now, and one of the biggest questions is just how many people will show up to vote. The margins in the 2020 election were razor thin in several swing states, and it's looking like that might happen once again. As a result, the "ground game," in which political parties talk to potential voters and try to persuade them to vote, is likely to play a large role.

Even in a tight, important presidential race, with the parties trying their best to get people to vote, a huge number of Americans don't bother to do so. That led me to wonder how many Americans do vote, how these numbers have changed over the years, and how this compares with voting numbers in other countries.

Data and six questions

To answer these questions, I took data from the International Institute for Democracy and Electoral Assistance, which calls itself "International IDEA" (https://www.idea.int/). International IDEA tries to help countries to become more democratic – including monitoring and encouraging women in leadership. We have looked at their data before, back in BW 69 (https://www.bambooweekly.com/bw-69-election-participation/ ).

International IDEA's "voter turnout database" is at

https://www.idea.int/data-tools/data/voter-turnout-database

Download the data by clicking on the "export data" button next to the headline on the page. This should download an Excel file onto your computer.

To see the data dictionary for this data set, click on the "glossary" link on the right side of the page, under the headline "background information."

Here are my solutions and explanations for this week; as always, a link to download my Jupyter notebook is at the bottom of this post.

Turn the first ("All") tab of the spreadsheet into a Pandas data frame. The Year column should be a datetime value. (Note: The dashes in the dates will make this tricky!) Use the "Country", "Election Type", and "Year" values for a three-level multi-index.

Before doing anything else, let's load Pandas:

import pandas as pd

Now that we've done that, I'll load the file into a data frame. To create a data from from an Excel file, we can use read_excel, indicating that we just want the "All" tab:


filename = 'idea_export_voter_turnout_database_region.xlsx'
df = pd.read_excel(filename,
                  sheet_name='All')

This is good, except that I also asked you to set it up with a multi-index containing "Country", "Election Type", and "Year". If this were a CSV file, we could name the columns we want in the index; with Excel, we need to pass a list of integers indicating which columns we want:


filename = 'idea_export_voter_turnout_database_region.xlsx'
df = pd.read_excel(filename,
                  sheet_name='All',
                  index_col=[0, 3, 4])

This works, but there's still one thing missing: The Date column (now part of our multi-index) still has a dtype of object, meaning that it refers to a Python object – in this case, a string. We can tell read_excel to treat one or more columns as datetime values by passing the column name to parse_dates:


filename = 'idea_export_voter_turnout_database_region.xlsx'
df = pd.read_excel(filename,
                  sheet_name='All',
                  parse_dates=['Year'],
                  index_col=[0, 3, 4])

Now, I said that it would be tricky to deal with the date... but that turns out not to be true! The above code works just fine, turning the Year column into a datetime dtype.

Why did I think it would be tricky? Because when I downloaded the file and imported it into Pandas, the - (minus sign) character wasn't separating the date components. Rather, it was an n-dash, a different character that looks extremely similar, but is distinct. In order to make that work in my original solution, I had passed the date_format keyword argument. Or at least that's what I thought: When I double checked my work while writing these solutions, I found that the dates used regular ol' minus signs, and that the dates were parsed just fine without any extra hints.

One of the nice things about Jupyter is that it allows us to repeat our steps. I run the notebook for each BW edition several times, restarting the kernel each time, to make sure that I'm not accidentally using variables or functions that I defined while performing experiments.

The result of this call to pd.read_excel is a data frame with 3,717 rows and 10 columns, as well as a three-part multi-index on the rows.

Turn columns whose values contain percent signs (%) and commas into float dtypes. Why can we not use an int dtype for all of these?

Next, I asked you to turn all of the columns with % or , in the numbers into columns with a float64 dtype. There are a few ways to do this, but my preference is to create a Python list of strings (i.e., the names of the columns) and iterate over them.

Within each column, we use the str.replace method with a regular expression to search for either % or ,, replacing the found character with an empty string. Once we've performed that replacement, we can invoke astype to get back a new series, which we assign back to the column it came from:


for column_name in ['Voter Turnout', 'VAP Turnout', 
                    'Invalid votes', 'Total vote',
                    'Registration', 'Voting age population', 
                    'Population']:
    print(f'Processing {column_name}')
    df[column_name] = (
        df[column_name]
        .str.replace(r'[%,]', '', regex=True)
        .astype(float)
    )

Pandas allows you to access columns either using dot notation (i.e., treating the column name as an attribute on the data frame's variable) or square brackets (i.e., putting the column name in a string in the brackets). I've never been a big fan of using dot notation, but in this case, we don't have a choice. Column names that contain spaces and other punctuation aren't legal attributes in Python, which means that we cannot name them with dot notation.

I can then run df.dtypes and get a full report demonstrating that we successfully changed the columns' dtypes:

ISO2                      object
ISO3                      object
Voter Turnout            float64
Total vote               float64
Registration             float64
VAP Turnout              float64
Voting age population    float64
Population               float64
Invalid votes            float64
Compulsory voting         object
dtype: object

Why did we convert all of the columns to floats, when some of them could have been integers? Because each column contains some NaN values, and NaN cannot be coerced into an integer format. Indeed, running df.isna().sum() tells us how many NaN values are in each column:

ISO2                      13
ISO3                      19
Voter Turnout            183
Total vote                81
Registration             168
VAP Turnout              133
Voting age population     65
Population                53
Invalid votes            851
Compulsory voting         13
dtype: int64

Unless we want to use Pandas extension types or PyArrow, both of which support nullable integers, we'll thus need to turn our NaN-containing columns into floats.

On what date did the most recent presidential election take place in each country?

First, we can keep only those rows for which the Election Type part of the ballot is Presidential. Here, I use the xs method, which allows us to select all rows (or columns) that match that value in that part of the multi-index:

(
    df
    .xs('Presidential', level='Election Type')
)

Now that I only have presidential election data, I want to perform a groupby operation, finding the max year for each country. Both Country and Year are in our multi-index; it turns out that groupby can handle the categorical column being in the index, but not the calculation column. We'll thus call reset_index, specifying level='Year', to move the Year part of the multi-index back into a regular column:

(
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
)

Now we can run a groupby, getting the maximum value of Year (i.e., the most recent year) for each country:

(
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
    .groupby('Country')['Year'].max()
)

This returns a series whose index contains country names, and whose values are the most recent presidential election date. We can now filter using a combination of .loc and lambda, keeping only those values that are more than five years ago. Note that we can compare with datetime values using strings; Pandas is smart enough to handle the comparison.

After grabbing those older values, we then run sort_values to get them in ascending order:

(
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
    .groupby('Country')['Year'].max()
    .loc[lambda s_: s_ < '2019-10-30']
    .sort_values()
)

Here's the result:

Country
Saint Kitts and Nevis                           1958-01-01
Bangladesh                                      1986-01-01
Somalia                                         1986-01-01
Estonia                                         1992-09-20
Angola                                          1992-09-30
Yugoslavia, FR/Union of Serbia and Montenegro   2004-01-01
State of Palestine                              2005-01-01
South Sudan                                     2010-01-01
Yemen                                           2012-01-01
Armenia                                         2013-02-19
Sudan                                           2015-01-01
Haiti                                           2016-11-20
Cameroon                                        2018-01-01
Ireland                                         2018-01-01
Mali                                            2018-08-12
Georgia                                         2018-11-28
Namibia                                         2019-01-01
Ukraine                                         2019-04-21
Afghanistan                                     2019-09-28
Name: Year, dtype: datetime64[ns]

Some of these very old results seem to be the result of a change in governmental systems, moving from a presidential to a parliamentary system. And in the case of Ireland, their president serves a seven-year term, with an optional second seven years. But in some cases, we see examples of countries whose leaders have decided that elections aren't something they really want or need, so they just remain in power.

Among countries that had presidential elections within the last 5 years, which 10 had the highest proportion of voters (i.e., the greatest VAP Turnout)? Does high voter turnout indicate a more democratic environment?

This question is similar to the previous one, in that we want to find countries with elections within a certain time frame. However, it's different, in that we want to then use a separate column (VAP Turnout) for performing calculations.

We'll start by again grabbing only rows with Presidential for the Election Type, using xs, then moving the Year part of the index back into a regular column:

    
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
)

Next, we'll keep only the two columns that we care about for this query, Year and VAP Turnout, using double square brackets:

    
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
    [['Year', 'VAP Turnout']]
)

Then things get a bit wild and weird: We'll sort the data frame (containing all presidential-election rows and the Year and VAP Turnout columns) by the Year column, from smallest (i.e., earliest) to largest (i.e., latest). The result will be the same values, but sorted in chronological order.

Then we run a groupby query. Normally, groupby takes a categorical column, and performs an aggregation method on a numeric column. If we don't specify a numeric column, then the aggregation method is applied to all columns.

In this case, our categorical column is Country, currently being used in the index. We'll then specify the aggregation method tail(1). Now, I've used tail for many years on both series and data frames, but this is the first time I've ever used it in the context of a groupby.

Basically, calling tail(1) on the groupby result object means: Give me, for each unique value of the categorical column (i.e., Country) the final row. Because we haven't restricted the columns we request, we'll thus get both Year and VAP Turnout back – one row for each country.

Moreover, because groupby doesn't change the order of the rows on which it works, and because we ran sort_values('Year') before performing the groupby, we'll get the most recent year's election info for each country:

    
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
    [['Year', 'VAP Turnout']]
    .sort_values('Year')
    .groupby('Country').tail(1)
)

Finally, we can use loc and lambda to keep only dates in the last five years, and then choose the 10 countries with the highest voter turnout using nlargest:

    
    df
    .xs('Presidential', level='Election Type')
    .reset_index(level='Year')
    [['Year', 'VAP Turnout']]
    .sort_values('Year')
    .groupby('Country').tail(1)
    .loc[lambda df_: df_['Year'] >= '2019-10-30']
    .nlargest(columns='VAP Turnout', n=10)
)

Here are the results I got:

                           Year  VAP Turnout
Country                                     
Rwanda               2024-07-15       117.03
Syrian Arab Republic 2021-01-01       114.77
Uruguay              2024-10-27        92.41
Seychelles           2020-01-01        88.83
Turkey               2023-05-28        88.27
Bolivia              2020-01-01        87.57
Maldives             2023-09-30        86.15
Ecuador              2023-10-15        86.08
Sri Lanka            2024-09-21        85.56
Turkmenistan         2022-01-01        84.44

Voter turnout in Rwanda and Syria were both very impressive, with more than 100 percent of the citizens voting! You could argue that they're putting into effect the old Chicago mantra of "vote early and often," but International IDEA says that such numbers might reflect poor record keeping and/or mismatches between when each data set was collected.

The countries that we found don't constitute the most inspiring democracies on the planet. I've heard that one of the reasons for low voter participation is that people feel like their countries are fairly stable, and that their votes thus won't change things very much – whereas in less stable, transparent democracies, people have a chance to change their leadership and improve their lives. Maybe so, but that doesn't seem to ring as true this year, when many incumbents have either lost elections or found themselves in narrower majorities.

It's often said that more Americans vote during presidential elections (i.e., every 4 years) than during congressional elections (i.e., every 2 years) when there isn't a presidential race. Compare the VAP turnout for congressional elections when there is and isn't a presidential contest.

Let's first find the mean VAP Turnout for Congressional races in years when there is a presidential election.

We'll start by invoking sort_index on our data frame. That might seem like a silly and unnecessary place to start, but when the index is sorted, .loc can use a variety of techniques to locate rows that match our search criteria. I thus kept getting warnings from Pandas, telling me that retrieving from an unsorted index was problematic. I still got the right answer, but if I can remove a warning, I will.

After sorting, I use the two-argument version of .loc to retrieve rows for the United States, and the column VAP Turnout:

(
    df
    .sort_index()
    .loc['United States', 'VAP Turnout']
)

This gives me a data frame with a three-part multi-index (country, election type, and year) and a single column. I want to keep only those rows in which there is both a congressional ("parliamentary") election and a presidential one. I thus use unstack to move the Election Type portion of the multi-index into the columns.

Instead of having a single column of data for both presidential and parliamentary elections, I'll now have two columns for each date, one with the VAP Turnout for the presidential election, and a second for the parliamentary election:

(
    df
    .sort_index()
    .loc['United States', 'VAP Turnout']
    .unstack('Election Type')
)

The resulting data frame looks like this:

Election Type  Parliamentary  Presidential
Year                                      
1946-01-01             38.78           NaN
1948-01-01             48.10         51.09
1950-01-01             42.64           NaN
1952-01-01             59.69         60.31
1954-01-01             43.15           NaN
1956-01-01             54.92         58.29
1958-01-01             44.53           NaN
1960-01-01             63.06         63.06
1962-01-01             47.27           NaN
1964-01-01             61.92         61.92
1966-01-01             48.38           NaN
1968-01-01             60.84         60.84
1970-01-01             46.60           NaN
1972-01-01             55.21         60.92
1974-01-01             38.23           NaN
1976-01-01             53.55         56.92
1978-01-01             37.20           NaN
1980-01-01             52.56         56.54
1982-01-01             39.79           NaN
1984-01-01             53.11         58.39
1986-01-01             36.40           NaN
1988-01-01             50.11         55.93
1990-01-01             36.52           NaN
1992-01-01             55.09         60.08
1994-01-01             38.78           NaN
1996-01-01             49.08         53.44
1998-01-01             34.74           NaN
2000-01-01             47.35         52.62
2002-01-01             35.09           NaN
2004-01-01             55.31         57.07
2006-01-01             37.32           NaN
2008-01-01             52.59         57.47
2010-01-01             38.51           NaN
2012-01-01             51.80         53.58
2014-01-01             32.98           NaN
2016-01-01             56.20         56.20
2018-01-01             47.49           NaN
2020-01-01             62.36         62.36

As you can see, years in which there were both congressional and presidential elections in the United States have percentages in both columns. And years in which there was only a congressional election have NaN in the presidential column. That NaN will be the key to performing our analysis.

To get the years in which there were both congressional and presidential elections, we'll use dropna. That will get rid of any row with even one NaN value in it. We can then grab the Parliamentary column, and run mean on it:

(
    df
    .sort_index()
    .loc['United States', 'VAP Turnout']
    .unstack('Election Type')
    .dropna()
    ['Parliamentary']
    .mean()
)

The result is np.float64(54.886842105263156), aka 54.89 percent. Not as high as Syria, but one can always dream.

What about turnout in the opposite cases, when there isn't any presidential race? We can modify our query slightly:

(
    df
    .sort_index()
    .loc['United States', 'VAP Turnout']
    .unstack('Election Type')
    .loc[lambda df_: df_['Presidential'].isna()]
    ['Parliamentary']
    .mean()
)

Instead of dropna, I used isna to keep only those rows in which the Presidential value is NaN. This returned the rows that we had previously thrown out. The result is np.float64(40.231578947368426), aka about 40 percent.

While the percentage of Americans voting for president is relatively low, the percentage voting in so-called "off-year elections," when there is no presidential race, is far smaller.

We sometimes hear that the proportion of people voting for president has gone down over the years. Is the VAP Turnout number lower or higher than it was in the past? Has that number consistently gone down or up with each election?

Finally, do we really see a drop in the percentage of people voting over the last few decades?

Let's start by comparing the percentage of people who voted in the most recent US presidential election with people who voted in the earliest one in the data set, in 1948.

We can get that by first using sort_index, and the by using loc to retrieve rows with United States and Presidential in the first and second parts of the multi-index. Notice that we use a tuple here; using a list won't work, because it means that we want to match multiple index entries, rather than more than one dimension in a single index entry.

We use the two-argument version of .loc, in which the first argument specifies the rows we want, and the second argument specifies the columns we want:

(
    df
    .sort_index()
    .loc[('United States', 'Presidential'), 'VAP Turnout']
)

This gives us a series in which the index contains years, and the values are from VAP Turnout in those years – all presidential election years:

Year
1948-01-01    51.09
1952-01-01    60.31
1956-01-01    58.29
1960-01-01    63.06
1964-01-01    61.92
1968-01-01    60.84
1972-01-01    60.92
1976-01-01    56.92
1980-01-01    56.54
1984-01-01    58.39
1988-01-01    55.93
1992-01-01    60.08
1996-01-01    53.44
2000-01-01    52.62
2004-01-01    57.07
2008-01-01    57.47
2012-01-01    53.58
2016-01-01    56.20
2020-01-01    62.36
Name: VAP Turnout, dtype: float64

Just looking, we can see that the first row (from 1948) shows 51 percent, as opposed to 2020, where it shows 62 percent. However, we can also use iloc to retrieve just the first and final elements in the series, passing the list [0, -1] :

(
    df
    .sort_index()
    .loc[('United States', 'Presidential'), 'VAP Turnout']
    .iloc[[0, -1]]
)

This returns two rows from that column. We can then see the difference between the first and last rows by invoking diff, which returns a new series whose index is identical to the input series, but whose values show by how much the values differ:

(
    df
    .sort_index()
    .loc[('United States', 'Presidential'), 'VAP Turnout']
    .iloc[[0, -1]]
    .diff()
)

The difference, as we can see, is 11.27 percent. In other words, the percentage of people who vote in US presidential races has increased by more than 10 percent since 1948 – which is definitely not what I was expecting.

I then asked if the percentage of people voting has gone up or down consistently. We can use diff on the entire data frame:

(
    df
    .sort_index()
    .loc[('United States', 'Presidential'), 'VAP Turnout']
    .diff()
)

This gives us the following:

Year
1948-01-01     NaN
1952-01-01    9.22
1956-01-01   -2.02
1960-01-01    4.77
1964-01-01   -1.14
1968-01-01   -1.08
1972-01-01    0.08
1976-01-01   -4.00
1980-01-01   -0.38
1984-01-01    1.85
1988-01-01   -2.46
1992-01-01    4.15
1996-01-01   -6.64
2000-01-01   -0.82
2004-01-01    4.45
2008-01-01    0.40
2012-01-01   -3.89
2016-01-01    2.62
2020-01-01    6.16
Name: VAP Turnout, dtype: float64

Notice that the result from diff always has NaN in the first row, and then shows us by how much each row differs from the previous one. But how can we find out how often the numbers have gone up or down from the previous year? We can compare the number with 0, getting a True value if it's greater than 0, and False otherwise.

Normally, we would use the > operator to do that. But we can't really invoke > inside of our method chain, can we? No, but we can use the method form of >, namely gt (not to be confused with the magic `__gt__` method that we can define on an object to implement >). We can say:

(
    df
    .sort_index()
    .loc[('United States', 'Presidential'), 'VAP Turnout']
    .diff()
    .gt(0)
    .value_counts()
)

The results:

VAP Turnout
False    10
True      9
Name: count, dtype: int64

In other words, voter turnout in the United States has gone up as often as it has gone down since 1948. That doesn't mean the magnitude has gone up and down equally in every year, but comparing the 2020 election with the 1948 election shows a greater percentage of people voting. And remember that this is a greater percentage of a much larger population, and that the voting age was lowered from 21 to 18 in 1971.

That's it for this week. Let me know what you thought of the data and analysis. And of course, if you're a US citizen, please don't forget to vote!

Meanwhile, here's a link to my Jupyter notebook: https://drive.google.com/file/d/17dbhHiRv8UFs6TGdEJ5AxGB76se_nkSD/view?usp=drive_link

Reuven