Spatial joins

Goals of this notebook:

  • Based on the countries and cities dataframes, determine for each city the country in which it is located.
  • To solve this problem, we will use the the concept of a 'spatial join' operation: combining information of geospatial datasets based on their spatial relationship.
In [ ]:
%matplotlib inline

import pandas as pd
import geopandas

pd.options.display.max_rows = 10
In [ ]:
countries = geopandas.read_file("zip://./data/ne_110m_admin_0_countries.zip")
cities = geopandas.read_file("zip://./data/ne_110m_populated_places.zip")
rivers = geopandas.read_file("zip://./data/ne_50m_rivers_lake_centerlines.zip")

Recap - joining dataframes

Pandas provides functionality to join or merge dataframes in different ways, see https://chrisalbon.com/python/data_wrangling/pandas_join_merge_dataframe/ for an overview and https://pandas.pydata.org/pandas-docs/stable/merging.html for the full documentation.

To illustrate the concept of joining the information of two dataframes with pandas, let's take a small subset of our cities and countries datasets:

In [ ]:
cities2 = cities[cities['name'].isin(['Bern', 'Brussels', 'London', 'Paris'])].copy()
cities2['iso_a3'] = ['CHE', 'BEL', 'GBR', 'FRA']
In [ ]:
cities2
In [ ]:
countries2 = countries[['iso_a3', 'name', 'continent']]
countries2.head()

We added a 'iso_a3' column to the cities dataset, indicating a code of the country of the city. This country code is also present in the countries dataset, which allows us to merge those two dataframes based on the common column.

Joining the cities dataframe with countries will transfer extra information about the countries (the full name, the continent) to the cities dataframe, based on a common key:

In [ ]:
cities2.merge(countries2, on='iso_a3')

But, for this illustrative example, we added the common column manually, it is not present in the original dataset. However, we can still know how to join those two datasets based on their spatial coordinates.

Recap - spatial relationships between objects

In the previous notebook 02-spatial-relationships.ipynb, we have seen the notion of spatial relationships between geometry objects: within, contains, intersects, ...

In this case, we know that each of the cities is located within one of the countries, or the other way around that each country can contain multiple cities.

We can test such relationships using the methods we have seen in the previous notebook:

In [ ]:
france = countries.loc[countries['name'] == 'France', 'geometry'].squeeze()
In [ ]:
cities.within(france)

The above gives us a boolean series, indicating for each point in our cities dataframe whether it is located within the area of France or not.
Because this is a boolean series as result, we can use it to filter the original dataframe to only show those cities that are actually within France:

In [ ]:
cities[cities.within(france)]

We could now repeat the above analysis for each of the countries, and add a column to the cities dataframe indicating this country. However, that would be tedious to do manually, and is also exactly what the spatial join operation provides us.

(note: the above result is incorrect, but this is just because of the coarse-ness of the countries dataset)

Spatial join operation

**SPATIAL JOIN** = *transferring attributes from one layer to another based on their spatial relationship*

Different parts of this operations: * The GeoDataFrame to which we want add information * The GeoDataFrame that contains the information we want to add * The spatial relationship we want to use to match both datasets ('intersects', 'contains', 'within') * The type of join: left or inner join ![](img/illustration-spatial-join.svg)

In this case, we want to join the cities dataframe with the information of the countries dataframe, based on the spatial relationship between both datasets.

We use the geopandas.sjoin function:

In [ ]:
joined = geopandas.sjoin(cities, countries, op='within', how='left')
In [ ]:
joined
In [ ]:
joined['continent'].value_counts()

Lets's practice!

We will again use the Paris datasets to do some exercises. Let's start importing them again:

In [ ]:
districts = geopandas.read_file("data/paris_districts_utm.geojson")
stations = geopandas.read_file("data/paris_sharing_bike_stations_utm.geojson")
EXERCISE: Make a plot of the density of bike stations by district

  • Determine for each bike station in which district it is located (using a spatial join!). Call the result `joined`.
  • Based on this result, calculate the number of bike stations in each district (e.g. using `groupby` method; you can use the `size` size method to know the size of each group).
    • Make sure the result is a DataFrame called `counts` with the columns 'district_name' and 'n_bike_stations'.
    • To go from a Series to a DataFrame, you can use the `reset_index` or `to_frame` method (both have a `name` keyword to specify a column name for the original Series values.
  • Add those counts to the original `districts` dataframe, creating a new `districts2` dataframe (tip: this is a merge operation).
  • Calculate a new column 'n_bike_stations_by_area'.
  • Make a plot showing the density in bike stations of the districts.

In [ ]:
# %load _solved/solutions/03-spatial-joins1.py
In [ ]:
# %load _solved/solutions/03-spatial-joins2.py
In [ ]:
# %load _solved/solutions/03-spatial-joins3.py
In [ ]:
# %load _solved/solutions/03-spatial-joins4.py
In [ ]:
# %load _solved/solutions/03-spatial-joins5.py
In [ ]:
# %load _solved/solutions/03-spatial-joins6.py
In [ ]:
# %load _solved/solutions/03-spatial-joins7.py

The overlay operation

In the spatial join operation above, we are not changing the geometries itself. We are not joining geometries, but joining attributes based on a spatial relationship between the geometries. This also means that the geometries need to at least overlap partially.

If you want to create new geometries based on joining (combining) geometries of different dataframes into one new dataframe (eg by taking the intersection of the geometries), you want an overlay operation.

In [ ]:
africa = countries[countries['continent'] == 'Africa']
In [ ]:
africa.plot()
In [ ]:
cities['geometry'] = cities.buffer(2)
In [ ]:
geopandas.overlay(africa, cities, how='difference').plot()
REMEMBER
* **Spatial join**: transfer attributes from one dataframe to another based on the spatial relationship * **Spatial overlay**: construct new geometries based on spatial operation between both dataframes (and combining attributes of both dataframes)