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 pgeocodeVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your Python environment is at version 3.10 or higher. Upgrade Python if necessary.
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())`.
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'`.
Install `thefuzz` as an extra dependency if fuzzy search is desired: `pip install "pgeocode[fuzzy]"`.
Install the package using pip: `pip install pgeocode`
Use a valid two-letter ISO country code (e.g., 'US', 'FR', 'GB', 'CA').
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.
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.
Use a valid and supported ISO-3166-1 alpha-2 country code (e.g., 'US', 'DE', 'FR') and ensure it is in uppercase.