Python with Pgeocode and Pandas. Postal codes to geo coordinates.

PiotrDev
2 min readMar 4, 2023

--

Photo by Kristina Tripkovic on Unsplash

In some projects, you may need to retrieve geo coordinates from the set of zip codes. pgeocode is a lightweight Python library for high-performance off-line querying of GPS coordinates, region name and municipality name from postal codes.

Distances between postal codes and general distance queries are also supported. The database in use includes postal codes for 83 countries.

source: https://pypi.org/project/pgeocode/

Let me quickly show you how to use pgeocode in one of the real projects where we are tasked to retrieve geo coordinates from the subset of zip codes.

  1. Let’s begin with installing pgeocode.
pip install pgeocode
or
conda install -c conda-forge pgeocode

2. Then, we import the key libraries for this little project.

import pandas as pd
import os
import pgeocode

3. And we import our data to pandas DataFrame to df variable

df = pd.read_excel('CH_Post.xlsx')
df

4. We are then storing zip codes column to postal_codes variable

postal_codes = df["PLZ"].values.astype('str').tolist()
postal_codes

5. Subsequently, we initiate our pgeocode library, indicating we are seeking coordinates from the zip codes in Switzerland (providing ISO country code)

nomi = pgeocode.Nominatim('ch')
swiss_post = nomi.query_postal_code(postal_codes)
swiss_post

6. The last step is to save our newly created dataset to a .csv file.

swiss_post.to_csv('CH_Post_with_geocoord.csv')

In the six easy steps, you retrieved geo coordinates from the set of zip codes using pandas and pgeocode.

--

--

PiotrDev

15 years in Payments | Banking | Finance (FT500). MBA Warwick Business School. Full Stack Developer (JS, React, Python) | www.piotrmaciejewski.com