Back to Blog

Python with Pgeocode and Pandas. Postal codes to geo coordinates

Piotr

Piotr

Founder

April 5, 2023
3 min read
mailbox

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.


You can read this on Medium here.

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

Check the source here.

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.

1pip install pgeocode
2or
3conda install -c conda-forge pgeocode
sh

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

1  import pandas as pd
2  import os
3  import pgeocode
python

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

1  df = pd.read_excel('CH_Post.xlsx')
2  df
python

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

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

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

1  nomi = pgeocode.Nominatim('ch')
2  swiss_post = nomi.query_postal_code(postal_codes)
3  swiss_post
python

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

1 swiss_post.to_csv('CH_Post_with_geocoord.csv')
python

CONCLUSION

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

Piotr

About Piotr

Founder

Results-driven and forward-thinking Senior Leader in Payments, Banking & Finance with expertise in AI, Full Stack Development, and Python programming.