Is there a way to get country code with pgeocode?

Viewed 1117

I have seen in the documentation of pgeocde (https://pypi.org/project/pgeocode/) that you first have to pass in the country code in order to get country information. However, I cannot find anything on getting the country information by passing parameters such as country name or country zip code. I am wondering if this is possible?

From documentation:

>>> import pgeocode

>>> nomi = pgeocode.Nominatim('fr')
>>> nomi.query_postal_code("75013")
postal_code               75013
country code                 FR
place_name             Paris 13
state_name        Île-de-France
state_code                   11
county_name               Paris
county_code                  75
community_name            Paris
community_code              751
latitude                48.8322
longitude                2.3561
accuracy                      5

So, instead of passing fr (which is a country code) as a parameter, is there a way to pass in the country name or zip code in order to get country information?

1 Answers

This library does not appear to have any functionality to begin with a zip code and derive the country. However, you could write a function to do this by by looping all the supported countries and seeing which ones have a postal_code that matches the one you have started with. To loop all possible countries, you reference pgeocode.COUNTRIES_VALID and do something like making a dictionary of each response:

import pgeocode
dfs = {}
for i in pgeocode.COUNTRIES_VALID:
   nomi = pgeocode.Nominatim(i)
   # this code will always return a dataframe
   # if the postal_code has no match, the df values will all be NaN 
   df = nomi.query_postal_code("75013")
   dfs[i] = df

Note that this approach will not be memory efficient. If you look at the source code for pgeocode (https://github.com/symerio/pgeocode/blob/master/pgeocode.py), you'll see that you could probably gain a lot of efficiency by indexing the underlying data and querying that index.

Related