14 Reprojecting and merging

In this lesson we will learn how to join data frames and will apply this to creating a choropleth map with geopandas.

By the end of this lesson, students will be able to:

  • write if-else statements to run different code depending on a condition
  • merge data frames using merge()
  • merge a pandas.DataFrame into a geopandas.GeoDataFrame without losing its geometry
  • create a choropleth map with geopandas
  • reproject a geopandas.GeoDataFrame using to_crs()
  • use a dataset’s metadata to anticipate and question the results of an analysis

About the data

The first dataset we will use is a list of Arctic communities and their location [1] created by the Alaska Native Tribal Health Consortium. Make sure to read the dataset’s abstract and portal page, we’ll use this information throughout the lesson.

The data comes in a GeoJSON file with the following attributes (as described on the website):

  • name: name of Arctic community
  • population: population of Arctic community, as of 2022
  • country: country that the Arctic community falls within (see dataset metadata for the codes)
  • geoname-id: numeric codes that uniquely identify all administrative/legal and statistical geographic areas for which the Census Bureau tabulates data
Check-in

Knowing what the data is about, do you notice anything peculiar about the metadata’s descriptions of the columns?

The second dataset is Natural Earth’s medium-scale cultural boundaries data for countries (1:50m) [2]. We can obtain this dataset by downloading the shapefile. Natural Earth is a public domain dataset with free, ready-to-use data for creating maps.

The third dataset we will use is a CSV file with the country codes and names of the Arctic countries in the Arctic communities dataset. This dataset was created for educational purposes for this lesson based on the metadata of the Arctic communities dataset and the country names in Natural Earth’s dataset. It can be accessed here.

Import data

We will first import the countries shapefile and adapt it for wrangling purposes:

import os
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd

# Import countries polygons
fp = os.path.join('data', 'ne_50m_admin_0_countries', 'ne_50m_admin_0_countries.shp')
countries = gpd.read_file(fp)

# Simplify column names
countries.columns = countries.columns.str.lower()

# Select columns for analysis
countries = countries[['admin', 'type', 'geometry']]

countries.head()
admin type geometry
0 Zimbabwe Sovereign country POLYGON ((31.28789 -22.40205, 31.19727 -22.344...
1 Zambia Sovereign country POLYGON ((30.39609 -15.64307, 30.25068 -15.643...
2 Yemen Sovereign country MULTIPOLYGON (((53.08564 16.64839, 52.58145 16...
3 Vietnam Sovereign country MULTIPOLYGON (((104.06396 10.39082, 104.08301 ...
4 Venezuela Sovereign country MULTIPOLYGON (((-60.82119 9.13838, -60.94141 9...
# Quick view
countries.plot()

Next, we import the Arctic communities data. Similar to how we previously used pandas.read_csv(), we can read in the Arctic communities GeoJSON data directly from the data repository using geopandas.read_file():

# Import Arctic communities data
URL = 'https://cn.dataone.org/cn/v2/resolve/urn%3Auuid%3Aed7718ae-fb0d-43dd-9270-fbfe80bfc7a4'
communities = gpd.read_file(URL)

communities.head()
name population country geoname-id geometry
0 Udomlya 32373 RU 452949 POINT (34.99250 57.87944)
1 Valmiera 26963 LV 453754 POINT (25.42751 57.54108)
2 Ventspils 42644 LV 454310 POINT (21.57288 57.38988)
3 Vec-Liepāja 85260 LV 454432 POINT (21.01667 56.53333)
4 Tukums 18348 LV 454768 POINT (23.15528 56.96694)

Both datasets use the EPSG:4326 CRS. Remember all GeoJSON files are given in this CRS and all points are expressed in longitude and latitude units of decimal degrees.

print(countries.crs)
EPSG:4326

Since the CRSs of our geospatial data match, it is easy to take a quick look at our communities data by plotting it on top of the countries data frame:

# Verify CRSs match
assert countries.crs == communities.crs

fig, ax = plt.subplots()
countries.plot(ax=ax)
communities.plot(ax=ax, color='red')
plt.show()

Finally, we import the country names and codes CSV:

# Import country names from URL
URL = 'https://raw.githubusercontent.com/MEDS-eds-220/MEDS-eds-220-course/refs/heads/main/book/chapters/lesson-12-merge-data/country_names.csv'
country_names = pd.read_csv(URL)
country_names.head()
country admin
0 RU Russia
1 LV Latvia
2 EE Estonia
3 LT Lithuania
4 SE Sweden

Arctic communities by country

Next, we want to calculate the number of Arctic communities by country.

# Create data frame with number of communities per country
n_comms = (communities.groupby('country')
                      .size()
                      .reset_index(name='n_communities'))

Let’s break this down:

  • We start with our communities data frame and use groupby('country') to group by country code.
  • Then we use size() as an aggregator function to calculate the size of each group.
  • The result of this operation is a pandas.Series indexed by the country values.
  • By resetting the index we transform the pandas.Series into a pandas.DataFrame; the index is now a column named country and the values of the series are named n_communities.
# Number of Arctic communities per country
n_comms
country n_communities
0 AX 1
1 BY 8
2 CA 7
3 DK 72
4 EE 14
5 FI 98
6 FO 1
7 GB 96
8 GL 1
9 IS 5
10 LT 26
11 LV 25
12 NO 48
13 RU 774
14 SE 133
15 US 115

if-else statements

Our goal is to merge the n_comms and the countries data frames. To merge two data frames they need to have at least one column in common. Currently our datasets do not have any columns in common:

set(countries.columns).intersection(n_comms.columns)
set()

The output set() represents the empty set. This might not be as informative, so let’s write a different notification:

common_columns = set(countries.columns).intersection(n_comms.columns)

# Check if there are any common columns
if len(common_columns) != 0:
    print(f"Common columns: {common_columns}")
else:
    print("No common columns")
No common columns

Remember that an if-else statement is a control structure that allows code to make decisions: it checks a condition, and if that condition is true, it executes one block of code (the if block); if the condition is false, it executes a different block (the else block). This enables programs to respond differently depending on specific criteria or inputs.

Check-in

Wrap up the previous code into a function called check_common_columns that prints a message depending on whether two data frames have common columns or not. Don’t forget to include a docstring!

Merging data frames

We can use the country_names data frame to add the country names into the n_comms data which, in turn, will allow us to merge that data frame with the countries data. To merge data frames we can use the pandas.merge() function. The basic syntax for it is:

output_df = pd.merge(left_df,
                     right_df, 
                     how = type_of_join, 
                     on = column_to_join)

where

  • output_df is the data frame resulting from the merge,
  • left_df is the data frame we have “on the left side”,
  • right_df is the data frame we have “on the right side”,
  • how specifies the type of join between the left and right data frames, (check the options here), the default is to do an inner join,
  • on specifies the column to join on; this column must be present in both our data frames.

The pandas.merge() function is also available as a method of data frames:

left_df.merge(right_df, how=..., on=...)

does the same as

pd.merge(left_df, right_df, how=..., on=...)

When one of the data frames is a geopandas.GeoDataFrame, GeoPandas recommends calling merge() from the geodataframe, so the output keeps its geometry. With pd.merge(), the geodataframe must be the left argument, otherwise you lose the geometry and the output is a plain pandas.DataFrame.

So, we merge the n_comms and country_names data frames using a left join:

Image source: Data Modeling Essentials, NCEAS Learning Hub [3]
n_comms = pd.merge(n_comms,
                   country_names,
                   how='left',
                   on='country')
n_comms
country n_communities admin
0 AX 1 Aland Islands
1 BY 8 Belarus
2 CA 7 Canada
3 DK 72 Denmark
4 EE 14 Estonia
5 FI 98 Finland
6 FO 1 Faroe Islands
7 GB 96 United Kingdom
8 GL 1 Greenland
9 IS 5 Iceland
10 LT 26 Lithuania
11 LV 25 Latvia
12 NO 48 Norway
13 RU 774 Russia
14 SE 133 Sweden
15 US 115 United States of America

We can reuse our function to check that n_comms and countries now have a common column on which we can merge them:

check_common_columns(n_comms, countries)
Common columns: {'admin'}
{'admin'}
Check-in

Create a new variable named arctic_countries which is the result of an inner join between our countries and n_comms data frames. The inner join will merge the subset of rows that have matches in both the left table and the right table.

Image source: Data Modeling Essentials, NCEAS Learning Hub [3]

Reviewing results

It is always a good idea to check the number of rows after a merge. Our n_comms data frame has one row per country, but the merged data frame has one row less:

print(f"Countries in n_comms: {len(n_comms)}")
print(f"Countries in arctic_countries: {len(arctic_countries)}")
Countries in n_comms: 16
Countries in arctic_countries: 15

An inner join only keeps the rows that have a match in both data frames, so one country in n_comms had no match in countries. We can find it using isin():

# Countries in n_comms without a match in countries
n_comms[~n_comms['admin'].isin(countries['admin'])]
country n_communities admin
0 AX 1 Aland Islands

The Aland Islands are an autonomous region of Finland and there is one Arctic community registered in this region. Like the Faroe Islands and Greenland, the Aland Islands have their own country code in the Arctic communities data and their own polygon in Natural Earth’s data. So why didn’t they match? Let’s look for them in the countries data frame:

countries[countries['admin'].str.contains('Aland')]
admin type geometry
168 Aland Country MULTIPOLYGON (((19.98955 60.35117, 20.02021 60...

Natural Earth’s data calls this region ‘Aland’, while our country_names data uses ‘Aland Islands’. The values in the column we join on must match exactly for the merge to find them. We update the name in n_comms to match the countries data and merge again:

# Match the name used in the countries data
n_comms['admin'] = n_comms['admin'].replace('Aland Islands', 'Aland')

# Merge again
arctic_countries = countries.merge(n_comms,
                                   how='inner',
                                   on='admin')
print(f"Countries in arctic_countries: {len(arctic_countries)}")
Countries in arctic_countries: 16

Checking with indicator=True

Another way to find rows without a match is to add indicator=True to the merge. This creates a _merge column that says whether each row was found in both data frames or only in one of them:

left = pd.DataFrame({'key': ['a', 'b', 'c'], 'x': [1, 2, 3]})
right = pd.DataFrame({'key': ['a', 'b', 'd'], 'y': [4, 5, 6]})

pd.merge(left, right, how='outer', on='key', indicator=True)
key x y _merge
0 a 1.0 4.0 both
1 b 2.0 5.0 both
2 c 3.0 NaN left_only
3 d NaN 6.0 right_only

Choropleth map

A choropleth map is an efficient way to visualize aggregate data per region.

Check-in

Re-read the dataset’s abstract. Which countries do you expect to have the most communities?

Making a choropleth map from our polygons GeoDataFrame is easy; we just need to specify the column parameter in plot() and make it equal to the column with the values we want to plot in each country:

arctic_countries.plot(column='n_communities',
                      legend=True)

Check-in

Compare the map with your predictions. Does this map show where people live in the Arctic, or how the communities were selected for this dataset? What title would describe the map more accurately?

Reprojecting

Remember that CRSs reflect cultural views and even biases. Any map projection involves choices about which areas to emphasize, minimize, or distort, and those choices can influence how viewers perceive different regions. In our map, using the EPSG:4326 CRS is, among other things, mapping the Arctic regions as far apart, while they are actually near each other.

Reprojecting means changing the coordinate reference system of your geospatial data. In our case, we will reproject the arctic_countries geodataframe to the CRS EPSG:3413. This CRS is a projected CRS, better suited for working with data from the Arctic region:

Changing CRSs in GeoPandas is very simple using the to_crs() method for geopandas.GeoDataFrames. The general syntax is:

updated_geodf = geodf.to_crs(new_crs)

where:

  • updated_geodf is the output of the method, a new geodataframe (to_crs() does not work in place),
  • geodf is the geopandas.GeoDataFrame we want to transform,
  • new_crs is the CRS we want to convert to; this is an object of type CRS or a string representing the CRS (ex: 'epsg:3413').

In our case:

# Reproject to CRS optimized for Arctic region
arctic_countries = arctic_countries.to_crs('epsg:3413')

We can now use the reprojected data to update our map:

Code
fig, ax = plt.subplots(figsize=(8, 6))

# Remove the axis for a cleaner map
ax.axis('off')

# Create choropleth map of communities
# Plot with refined color and edge style
arctic_countries.plot(
    ax=ax,
    column='n_communities',
    cmap='PuBuGn',
    legend=True,
    edgecolor="0.6",
    linewidth=0.5,
    legend_kwds={
        "shrink": 0.7,
        "label": "Number of Communities",
        "orientation": "horizontal",
        "pad": 0.05
    }
)

# Add title for better context
ax.set_title('Communities at or above 55°N, 2022\n(at least 10,000 people; 500 in Alaska)',
             fontsize=14, weight='bold', pad=15)

plt.show()

Check-in

Critique this map. What does it do well, what could mislead a reader, and what would you change to improve it? Consider both the data and the design choices.

Although the new projection clearly improves the presentation of the data, there are still issues with this plot! Mainly, the entire United States territory is in it, when we should only have Alaska. In our next lesson we will review strategies to clip and subset vector data and return to this plot in our discussion section.

References

[1]
M. Brook, “Approximate Arctic Communities and Populations, (latitude >= 55, 2022).” Arctic Data Center, 2023. doi: 10.18739/A28S4JQ80. Available: https://arcticdata.io/catalog/view/doi:10.18739/A28S4JQ80. [Accessed: Nov. 03, 2024]
[2]
Natural Earth, “Admin 0 – Countries, 1:50m Cultural Vectors.” Dataset, version 5.1.1, 2022. Available: https://www.naturalearthdata.com/downloads/50m-cultural-vectors/
[3]
H. Do-Linh, C. Galaz García, M. B. Jones, and C. Vargas Poulsen, Open Science Synthesis training Week 1. NCEAS Learning Hub & Delta Stewardship Council. 2023. Available: https://learning.nceas.ucsb.edu/2023-06-delta/