The world’s leading publication for data science, AI, and ML professionals.

Tagging a Location to a Shapefile Area using Geopandas

Another geospatial use case made easy by GeoPandas

Photo by Marjan Blan | @marjanblan on Unsplash
Photo by Marjan Blan | @marjanblan on Unsplash

I previously wrote about a simple way to plot maps using Geopandas and Matplotlib.

A Beginners Guide to Create a Choropleth Map in Python using GeoPandas and Matplotlib

Now another very common Geospatial analytics use case is to tag a specific location to a predetermined location/area/region/etc. For example, let’s say you are an analyst for a brick-and-mortar store that wants to map the amount of competition in their key areas. These key areas can either be a business predefined area or based on predetermined country regions (like a province, district, etc.).

Your team already collected enough list of competitor addresses and their lat-long coordinates. Either purchased from a third-party company, or an arduous Google Search exercise, or both. So now you are tasked with mapping these addresses’ latitude and longitude with let’s say, a custom city name. Your company already has the shapefile containing the strategically drawn borders. All you need to do is to tag the City name to competitors’ locations.

You don’t need any fancy algorithm, GeoPandas package already got your back!

For this exercise, we will use the Indonesian province shapefile which you can get here, and some random Indonesian malls’ addresses that I gathered. You can get it along with the complete source code at my Github repo.

The first step would be to load our required packages and then our reference shapefile and list of addresses that we would like to tag.

Indonesian Province reference shapefile - Source from Author
Indonesian Province reference shapefile – Source from Author
Addresses Coordinates to be Tagged - Source from Author
Addresses Coordinates to be Tagged – Source from Author

Now, Geopandas is actually a very powerful geospatial package that makes this task so easy. It already provides us with the within command so we only a few short lines of codes!

Address Tagging Result - Source from Author
Address Tagging Result – Source from Author

The within code checks if our addresses’ latitude and longitude points are within our reference shapefile. Note that we need to check it with one province reference at a time. Otherwise, we would not be able to properly tag it (since two addresses can be in two different provinces, we would have difficulty correctly tagging it if we did it on all references at once).

And that’s it! Hopes this tutorial can be of use to your geospatial analysis. For the full source code and data, you can check them out on my Github repo.


Related Articles