{ "cells": [ { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "# Geocoding in Geopandas\n", "\n", "It is possible to do [geocoding in Geopandas](http://geopandas.org/geocoding.html) using its integrated functionalities of geopy. Geopandas has a function called `geocode()` that can geocode a list of addresses (strings) and return a GeoDataFrame containing the resulting point objects in ``geometry`` column. \n", "\n", "Nice, isn't it! Let's try this out.\n", "\n", "We will geocode addresses stored in a text file called `addresses.txt`. The addresses are located in the Helsinki Region in Southern Finland.\n", "\n", "The first rows of the data look like this:\n", "\n", "```\n", "id;addr\n", "1000;Itämerenkatu 14, 00101 Helsinki, Finland\n", "1001;Kampinkuja 1, 00100 Helsinki, Finland\n", "1002;Kaivokatu 8, 00101 Helsinki, Finland\n", "1003;Hermannin rantatie 1, 00580 Helsinki, Finland\n", "```\n", "\n", "We have an `id` for each row and an address on column `addr`.\n", "\n", "- Let's first read the data into a Pandas DataFrame using the `read_csv()` -function:\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "deletable": true, "editable": true }, "outputs": [], "source": [ "# Import necessary modules\n", "import pandas as pd\n", "import geopandas as gpd\n", "from shapely.geometry import Point\n", "\n", "# Filepath\n", "fp = r\"data/addresses.txt\"\n", "\n", "# Read the data\n", "data = pd.read_csv(fp, sep=';')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Let's check that we imported the file correctly:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "34" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(data)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idaddr
01000Itämerenkatu 14, 00101 Helsinki, Finland
11001Kampinkuja 1, 00100 Helsinki, Finland
21002Kaivokatu 8, 00101 Helsinki, Finland
31003Hermannin rantatie 1, 00580 Helsinki, Finland
41005Tyynenmerenkatu 9, 00220 Helsinki, Finland
\n", "
" ], "text/plain": [ " id addr\n", "0 1000 Itämerenkatu 14, 00101 Helsinki, Finland\n", "1 1001 Kampinkuja 1, 00100 Helsinki, Finland\n", "2 1002 Kaivokatu 8, 00101 Helsinki, Finland\n", "3 1003 Hermannin rantatie 1, 00580 Helsinki, Finland\n", "4 1005 Tyynenmerenkatu 9, 00220 Helsinki, Finland" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.head()" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "## Geocode addresses using Nominatim\n", "\n", "Now we have our data in a Pandas DataFrame and we can geocode our addresses using the [geopandas geocoding function](http://geopandas.org/reference/geopandas.tools.geocode.html#geopandas-tools-geocode). `geopandas.tools.geocode` uses `geopy` package in the background. \n", "\n", "- Let's import the geocoding function and geocode the addresses (column `addr`) using Nominatim. \n", "- Remember to provide a custom string (name of your application) in the user_agent parameter.\n", "- If needed, you can add the `timeout`-parameter which specifies how many seconds we will wait for a response from the service." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "# Import the geocoding tool\n", "from geopandas.tools import geocode\n", "\n", "# Geocode addresses using Nominatim. Remember to provide a custom \"application name\" in the user_agent parameter!\n", "geo = geocode(data['addr'], provider='nominatim', user_agent='autogis_xx', timeout=4)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
addressgeometry
0Ruoholahti, 14, Itämerenkatu, Ruoholahti, Läns...POINT (24.9155624 60.1632015)
1Kamppi, 1, Kampinkuja, Kamppi, Eteläinen suurp...POINT (24.9316914 60.1690222)
2Bangkok9, 8, Kaivokatu, Keskusta, Kluuvi, Etel...POINT (24.9416849 60.1699637)
3Hermannin rantatie, Kyläsaari, Hermanni, Helsi...POINT (24.9719335 60.1969965)
4Hesburger, 9, Tyynenmerenkatu, Jätkäsaari, Län...POINT (24.9216003 60.1566475)
\n", "
" ], "text/plain": [ " address \\\n", "0 Ruoholahti, 14, Itämerenkatu, Ruoholahti, Läns... \n", "1 Kamppi, 1, Kampinkuja, Kamppi, Eteläinen suurp... \n", "2 Bangkok9, 8, Kaivokatu, Keskusta, Kluuvi, Etel... \n", "3 Hermannin rantatie, Kyläsaari, Hermanni, Helsi... \n", "4 Hesburger, 9, Tyynenmerenkatu, Jätkäsaari, Län... \n", "\n", " geometry \n", "0 POINT (24.9155624 60.1632015) \n", "1 POINT (24.9316914 60.1690222) \n", "2 POINT (24.9416849 60.1699637) \n", "3 POINT (24.9719335 60.1969965) \n", "4 POINT (24.9216003 60.1566475) " ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "geo.head()" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "And Voilà! As a result we have a GeoDataFrame that contains our original\n", "address and a 'geometry' column containing Shapely Point -objects that\n", "we can use for exporting the addresses to a Shapefile for example.\n", "However, the ``id`` column is not there. Thus, we need to join the\n", "information from ``data`` into our new GeoDataFrame ``geo``, thus making\n", "a **Table Join**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Rate-limiting**\n", "\n", "When geocoding a large dataframe, you might encounter an error when geocoding. In case you get a time out error, try first using the `timeout` parameter as we did above (allow the service a bit more time to respond). In case of Too Many Requests error, you have hit the rate-limit of the service, and you should slow down your requests. To our convenience, GeoPy provides additional tools for taking into account rate limits in geocoding services. This script adapts the usage of [GeoPy RateLimiter](https://geopy.readthedocs.io/en/stable/#geopy.extra.rate_limiter.RateLimiter) to our input data:\n", "\n", "```\n", "from geopy.geocoders import Nominatim\n", "from geopy.extra.rate_limiter import RateLimiter\n", "from shapely.geometry import Point\n", "\n", "# Initiate geocoder\n", "geolocator = Nominatim(user_agent='autogis_xx')\n", "\n", "# Create a geopy rate limiter:\n", "geocode_with_delay = RateLimiter(geolocator.geocode, min_delay_seconds=1)\n", "\n", "# Apply the geocoder with delay using the rate limiter:\n", "data['temp'] = data['addr'].apply(geocode_with_delay)\n", "\n", "# Get point coordinates from the GeoPy location object on each row:\n", "data[\"coords\"] = data['temp'].apply(lambda loc: tuple(loc.point) if loc else None)\n", "\n", "# Create shapely point objects to geometry column:\n", "data[\"geometry\"] = data[\"coords\"].apply(Point)\n", "```\n", "All in all, remember that Nominatim is not meant for super heavy use. \n", "
\n" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "## Table join\n", "\n", "
\n", "\n", "**Table joins in pandas**\n", " \n", "For a comprehensive overview of different ways of combining DataFrames and Series based on set theory, have a look at pandas documentation about [merge, join and concatenate](https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html).\n", "\n", "\n", "
\n", "\n", "\n", "Table joins are really common procedures when doing GIS analyses. As you might remember from our earlier lessons, combining data from different tables based on common\n", "**key** attribute can be done easily in Pandas/Geopandas using the [.merge()](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html) -function. We used this approach in the geo-python course [exercise 6](https://geo-python.github.io/2018/lessons/L6/exercise-6.html#joining-data-from-one-dataframe-to-another).\n", "\n", "However, sometimes it is useful to join two tables together based on the **index** of those DataFrames. In such case, we assume\n", "that there is **same number of records** in our DataFrames and that the **order of the records should be the same** in both DataFrames.\n", "In fact, now we have such a situation as we are geocoding our addresses where the order of the geocoded addresses in ``geo`` DataFrame is the same\n", "as in our original ``data`` DataFrame.\n", "\n", "Hence, we can join those tables together with ``join()`` -function which merges the two DataFrames together\n", "based on index by default." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
addressgeometryidaddr
0Ruoholahti, 14, Itämerenkatu, Ruoholahti, Läns...POINT (24.9155624 60.1632015)1000Itämerenkatu 14, 00101 Helsinki, Finland
1Kamppi, 1, Kampinkuja, Kamppi, Eteläinen suurp...POINT (24.9316914 60.1690222)1001Kampinkuja 1, 00100 Helsinki, Finland
2Bangkok9, 8, Kaivokatu, Keskusta, Kluuvi, Etel...POINT (24.9416849 60.1699637)1002Kaivokatu 8, 00101 Helsinki, Finland
3Hermannin rantatie, Kyläsaari, Hermanni, Helsi...POINT (24.9719335 60.1969965)1003Hermannin rantatie 1, 00580 Helsinki, Finland
4Hesburger, 9, Tyynenmerenkatu, Jätkäsaari, Län...POINT (24.9216003 60.1566475)1005Tyynenmerenkatu 9, 00220 Helsinki, Finland
\n", "
" ], "text/plain": [ " address \\\n", "0 Ruoholahti, 14, Itämerenkatu, Ruoholahti, Läns... \n", "1 Kamppi, 1, Kampinkuja, Kamppi, Eteläinen suurp... \n", "2 Bangkok9, 8, Kaivokatu, Keskusta, Kluuvi, Etel... \n", "3 Hermannin rantatie, Kyläsaari, Hermanni, Helsi... \n", "4 Hesburger, 9, Tyynenmerenkatu, Jätkäsaari, Län... \n", "\n", " geometry id \\\n", "0 POINT (24.9155624 60.1632015) 1000 \n", "1 POINT (24.9316914 60.1690222) 1001 \n", "2 POINT (24.9416849 60.1699637) 1002 \n", "3 POINT (24.9719335 60.1969965) 1003 \n", "4 POINT (24.9216003 60.1566475) 1005 \n", "\n", " addr \n", "0 Itämerenkatu 14, 00101 Helsinki, Finland \n", "1 Kampinkuja 1, 00100 Helsinki, Finland \n", "2 Kaivokatu 8, 00101 Helsinki, Finland \n", "3 Hermannin rantatie 1, 00580 Helsinki, Finland \n", "4 Tyynenmerenkatu 9, 00220 Helsinki, Finland " ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "join = geo.join(data)\n", "join.head()" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "- Let's also check the data type of our new ``join`` table." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/plain": [ "geopandas.geodataframe.GeoDataFrame" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(join)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "As a result we have a new GeoDataFrame called ``join`` where we now have\n", "all original columns plus a new column for ``geometry``. **Note!** If you would do the join the other way around, i.e. `data.join(geo)`, the output would be a pandas DataFrame, not a GeoDataFrame!\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Now it is easy to save our address points into a Shapefile" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "deletable": true, "editable": true }, "outputs": [], "source": [ "# Output file path\n", "outfp = r\"data/addresses.shp\"\n", "\n", "# Save to Shapefile\n", "join.to_file(outfp)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "That's it. Now we have successfully geocoded those addresses into Points\n", "and made a Shapefile out of them. Easy isn't it!" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Notes about Nominatim\n", "\n", "Nominatim works relatively nicely if you have well defined and well-known addresses such as the ones that we used in this tutorial. In practice, the address needs to exist in the OpenStreetMap database. Sometimes, however, you might want to geocode a \"point-of-interest\", such as a museum, only based on it's name. If the museum name is not on OpenStreetMap, Nominatim won't provide any results for it, but you might be able to geocode the place using some other geocoder such as the [Google Geocoding API (V3)](https://developers.google.com/maps/documentation/geocoding/), which requires an API key. [Take a look from past year's materials where we show how to use Google Geocoding API](https://automating-gis-processes.github.io/2016/Lesson3-geocoding.html#geocoding-in-geopandas) in a similar manner as we used Nominatim here." ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [default]", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.6" } }, "nbformat": 4, "nbformat_minor": 4 }