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 osimport pandas as pdimport matplotlib.pyplot as pltimport geopandas as gpd# Import countries polygonsfp = os.path.join('data', 'ne_50m_admin_0_countries', 'ne_50m_admin_0_countries.shp')countries = gpd.read_file(fp)# Simplify column namescountries.columns = countries.columns.str.lower()# Select columns for analysiscountries = 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 viewcountries.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():
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:
Finally, we import the country names and codes CSV:
# Import country names from URLURL ='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 countryn_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 countryn_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:
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 columnsiflen(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]
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.
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 countriesn_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:
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 datan_comms['admin'] = n_comms['admin'].replace('Aland Islands', 'Aland')# Merge againarctic_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:
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:
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 regionarctic_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 mapax.axis('off')# Create choropleth map of communities# Plot with refined color and edge stylearctic_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 contextax.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.
H. Do-Linh, C. Galaz García, M. B. Jones, and C. Vargas Poulsen, Open ScienceSynthesis training Week 1. NCEASLearningHub & DeltaStewardshipCouncil. 2023. Available: https://learning.nceas.ucsb.edu/2023-06-delta/