Registry / data / pgeocode

pgeocode

JSON →
library0.5.0pypypi✓ verified 22d ago

pgeocode is a Python library for high-performance off-line querying of GPS coordinates, region name, and municipality name from postal codes. It also supports distance calculations between postal codes. The library utilizes the GeoNames database, covering 83 countries. The current version is 0.5.0. It has an active maintenance schedule with new releases that increment with feature additions and bug fixes.

pip install pgeocode
INSTALL
IMPORT
SIG · PGEOCODE
P
pgeocode
datapythonv0.5.0
Install
8.2s avg
Import
923ms
Disk
168MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.932s · 167.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 8.2s · import 0.914s · 160MB
168MB installed
● package 168MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pgeocode
import pgeocode
Nominatim
from pgeocode import Nominatim
GeoDistance
from pgeocode import GeoDistance

This quickstart demonstrates how to use `pgeocode.Nominatim` for querying postal code and location data, and `pgeocode.GeoDistance` for calculating distances between postal codes for a specified country. The data is downloaded and cached locally on first use. You can optionally set the `PGEOCODE_DATA_DIR` environment variable to control where the data is stored.

import pgeocode import os # Set a temporary data directory for demonstration if desired # os.environ['PGEOCODE_DATA_DIR'] = '/tmp/pgeocode_data' # Initialize Nominatim for a specific country (e.g., France) nomi = pgeocode.Nominatim('fr') # Query a single postal code paris_13 = nomi.query_postal_code('75013') print(f"Paris 13 details:\n{paris_13}\n") # Query multiple postal codes multiple_cities = nomi.query_postal_code(['75013', '69006']) print(f"Multiple cities details:\n{multiple_cities}\n") # Initialize GeoDistance for a specific country dist = pgeocode.GeoDistance('fr') # Calculate distance between two postal codes distance_km = dist.query_postal_code('75013', '69006') print(f"Distance between 75013 and 69006: {distance_km:.2f} km") # Example of using query_location (requires 'thefuzz' optional dependency for fuzzy matching) # If 'thefuzz' is not installed, it will perform exact matches. # To install: pip install "pgeocode[fuzzy]" # anti_data = nomi.query_location("Antibes", top_k=3) # print(f"Antibes locations:\n{anti_data}\n")
Debug
Known issues
breakingThe minimum required Python version has been updated. Version 0.4.0 required Python 3.8+, while the current version 0.5.0 requires Python 3.10+.
fix
Ensure your Python environment is at version 3.10 or higher. Upgrade Python if necessary.
affects: 0.4.x -> 0.5.0
gotcha`GeoDistance.query_postal_code` expects postal codes as Python lists when querying multiple codes, not NumPy arrays (e.g., directly from pandas Series).
fix
When passing a pandas Series to `query_postal_code`, convert it to a list using `.to_list()`. Example: `dist.query_postal_code(df['postal_code_1'].to_list(), df['postal_code_2'].to_list())`.
affects: All versions
gotchaData files for each country are downloaded and cached locally. By default, this cache is stored in `~/.cache/pgeocode/`. If this directory is not writable or needs to be controlled (e.g., in a containerized environment), downloads might fail.
fix
Set the `PGEOCODE_DATA_DIR` environment variable to a desired writable directory before initializing `pgeocode` objects. For example: `os.environ['PGEOCODE_DATA_DIR'] = '/path/to/writable/cache'`.
affects: All versions
gotchaWhen `Nominatim.query_location` is used for fuzzy searching by place name, the optional `thefuzz` package is required. Without it, only exact matches will be performed.
fix
Install `thefuzz` as an extra dependency if fuzzy search is desired: `pip install "pgeocode[fuzzy]"`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pgeocode'
The 'pgeocode' library has not been installed in the Python environment, or the environment where the code is run does not have it installed.
fix
Install the package using pip: `pip install pgeocode`
ValueError: Unknown country code
The country code provided to `pgeocode.Nominatim()` or `pgeocode.GeoDistance()` is not a valid ISO 3166-1 alpha-2 code supported by the GeoNames database used by pgeocode, or it's a non-standard variant like 'NL_FULL'.
fix
Use a valid two-letter ISO country code (e.g., 'US', 'FR', 'GB', 'CA').
urllib.error.HTTPError: HTTP Error 404: Not Found
During its first use for a specific country, `pgeocode` attempts to download GeoNames data, but the download URL is temporarily unavailable, incorrect, or the file has been moved on the GeoNames server.
fix
This issue often resolves itself when GeoNames updates its servers. You can also try ensuring a stable internet connection or checking the pgeocode GitHub repository for updated download URLs or known data issues. Setting the `PGEOCODE_DATA_DIR` environment variable to a writable directory can prevent permission-related download failures.
pgeocode query_postal_code returns NaN / pgeocode not returning CA locations
`pgeocode` relies on the GeoNames database, which may have incomplete, outdated, or specifically formatted data for certain countries or postal codes, leading to `NaN` results even for seemingly valid inputs.
fix
Verify that the postal code format precisely matches the expected format for the specified country. For critical or frequently updated postal code data, consider supplementing `pgeocode` with external APIs that provide more current or comprehensive data for specific regions.
ValueError: Country with code 'XX' not supported.
The provided country code for `pgeocode.Nominatim` is either invalid, not supported by GeoNames, or not in the correct uppercase ISO-3166-1 alpha-2 format.
fix
Use a valid and supported ISO-3166-1 alpha-2 country code (e.g., 'US', 'DE', 'FR') and ensure it is in uppercase.
Upgrade
Version history
0.5.0latest on PyPI · released Apr 13, 2024
Audit
Dependencies
pandasrequiredRequired for data handling and the DataFrame output format.
thefuzzoptionalOptional dependency for fuzzy search functionality in `Nominatim.query_location`.
Agent activity
9 hits · last 30 days
node
8
Resources