Checking if Points In Polygon (State) and Mapping the State

Question:

I am trying to map Point data to geographic locations (i.e. US states).

I want to create a ‘States’ column by checking if the points fall within certain states using geojson data that has the polygon data in shapely geometry format, and the US States that the polygon data is.

I can’t seem to get the logic right to get this to work. Here’s what I’ve attempted:

def map_states(row):
for ind, row in dfpoly.iterrows():
    polygon = shape(row['geometry'])
    if polygon.contains(dfpoints['Point'][ind]):
        return dfpoly['state']

then once the logic is correct, I would like to use apply to create the states column in my data:

dfpoints['states'] = dfpoints.apply(map_states, axis=1)

Appreciate any help. Thanks!

Asked By: Electronic_Tear

||

Answers:

To correct/test your logic, compare yours with this.

import geopandas as gpd

city_pnts = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))
country_pgns = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))

def inside_country( city_point_geom ):
    for indx, row in country_pgns.iterrows():
        pgon = row.geometry
        country_name = row["name"]
        if pgon.contains(city_point_geom):
            print(country_name)
            return country_name
        else:
            #print("Fails!")
            pass
        pass

Run the code above, follow by this code.

# Get one of a city's geometry by number
# and check what country it is inside

number = 20
inside_country(city_pnts.geometry.values[number])

This returns:

'Switzerland'

If you use more recent version of geopandas, try this

result1_gdf = city_pnts.sjoin(country_pgns)
result2_gdf = country_pgns.sjoin(city_pnts)

and see what you get inside result1/2_gdf geodataframes.

Answered By: swatchai