Geopandas Hands-on: Geospatial Relations and Operations
By: Juan Nathaniel
Tags: Machine Learning, GIS, Deep Learning, Artificial Intelligence, Data Science

Geopandas Hands-on: Geospatial Relations and Operations

Part 1: Introduction to geospatial concepts (follow here)

Part 2: Geospatial visualization and geometry creation (follow here)

Part 3: Geospatial operations (this post)

Part 4: Building geospatial machine learning pipeline (follow here)

In the two previous posts we have discussed the basics of geopandas and how to visualize geospatial dataset. Here, we are going to introduce the basic concepts of geospatial operations including those of relations and spatial joins.

Table of Content:

Recap Geospatial relations Spatial joins

Recap

Before we proceed with the tutorial, ensure that we restore the previous posts’ geodataframes.

# Import the necessary libraries

import geopandas

import shapely.geometry

import matplotlib.pyplot as plt # Initialize our geodataframe (gdf)

path_to_data = gpd.datasets.get_path("nybb")

gdf = gpd.read_file(path_to_data) # Set borough name as index

gdf = gdf.set_index("BoroName") # Get buffered region and centroid points

gdf["buffered"] = gdf.buffer(10000)

gdf['centroid'] = gdf.centroid

Now that the preliminary steps have been settled, let’s begin with the tutorial.

Geospatial relations

Geometries, such as the polygons that define the individual borough or lines that represent the boundaries between the regions or points to indicate the centroid positions, can be related to one another.

A. Intersects

Suppose we ask the following question: does the buffer region intersect with Brooklyn borough in New York?

First we get the polygon for Brooklyn

brooklyn = gdf.loc["Brooklyn", "geometry"]

Brooklyn borough

We can then check if the buffered region intersects it.

gdf["buffered"].intersects(brooklyn) >>BoroName

>>Staten Island True

>>Queens True

>>Brooklyn True

>>Manhattan True

>>Bronx False

>>dtype: bool

It seems that Bronx is very far away from the Brooklyn that a buffer area of 10,000 feet beyond the boundary does not intersect Brooklyn at all.

B. Within

Another question could similarly arise: are the centroids contained in their respective boroughs (ie. unique centroids)? This could be performed by within relation that specifies whether a collection of points are contained in the said polygons.

gdf["centroid"].within(brooklyn) >>BoroName

>>Staten Island False

>>Queens False

>>Brooklyn True

>>Manhattan False

>>Bronx False

>>dtype: bool

To be expected, the centroid of Brooklyn is located within Brooklyn polygon and not within the other regions.

Spatial joins

Another important geospatial operations that we could perform with geopandas is spatial joins. As the name suggests, it allows two distinct geometries to be connected based on certain geometric criteria.

Let us suppose we have a few bus stations within the area, and we wanted to identify the borough in which each of the station lies.

# Generate some points

b = [int(x) for x in gdf.total_bounds]

N = 6 pointdf = gpd.GeoDataFrame([

{'geometry': shapely.geometry.Point(x, y), 'value1': x + y, 'value2': x - y}

for x, y in zip(range(b[0], b[2], int((b[2] - b[0]) / N)),

range(b[1], b[3], int((b[3] - b[1]) / N)))]) # Make sure they're using the same projection reference

pointdf.crs = gdf.crs

Randomly generated bus stations

The first solution that comes to mind would be to perform a within operation as before, and then for each borough, the True index value will assigned to that point (eg. if bus station 1 is within Brooklyn, assigns Brooklyn to the point item). Visually, it can illustrated as:

The spatial join can then be performed as follows:

from geopandas.tools import sjoin # Joining the NYC borough INTO the pointdf

sjoin(pointdf, gdf, how="left", op="intersects") # The NaNs are the points that do not intersect with any borough

Or if you want to drop the NaNs, performing an inner join could be done instead.

sjoin(pointdf, gdf, how="inner", op="intersects")

Conclusion

That’s it! Hope you learn something new today. In the next post, we will finally be ready to build our very first geospatial machine learning pipeline. Stay tuned!