Search code examples
pythongeolocationgeopandasgeocode

Creating a GeoDataFrame using postcodes


I have a dataframe where each row contains a location specified with a name and a postcode.

Example:

Name1; Postcode1;

Name2; Postcode2;

NameX; PostcodeX;

In order to produce a map where each of these rows show as a point, I need to create a GeoDataFrame using those postcodes (ideally without having to manually look for their latitude/longitude). What's the best way of doing so? Can it be done directly through GeoPandas?

So far, I'm only able to create the GeoDataFrame by using the coordinates of each point, which I have to look up manually on internet:

gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df['Long'], df1['Lat']), crs='EPSG:4326')

Where 'df' is the dataframe with the locations.

Thanks in advance :)


Solution

  • you can use pgeocode to lookup coords from postal codes.

    import pandas as pd 
    import pgeocode
    
    df = pd.DataFrame({'zips': [90210, 60606, 33162]})
    
    # lookup United States zipcodes
    nomi = pgeocode.Nominatim('us')
    
    df['lat'] = df['zips'].apply(lambda x: nomi.query_postal_code(x).latitude)
    df['long'] = df['zips'].apply(lambda x: nomi.query_postal_code(x).longitude)
    
    df
    
        zips      lat      long
    0  90210  34.0901 -118.4065
    1  60606  41.8868  -87.6386
    2  33162  25.9286  -80.1830