Reputation: 685
I have a list of named polygons:
import pandas as pd
import geopandas as gp
df = gp.GeoDataFrame([['a',Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b',Polygon([(1, 1), (2,2), (3,1)])]],
columns = ['name','geometry'])
df = gp.GeoDataFrame(df, geometry = 'geometry')
and a list of named points:
points = gp.GeoDataFrame( [['box', Point(1.5, 1.75)],
['cone', Point(3.0,2.0)],
['triangle', Point(2.5,1.25)]],
columns=['id', 'geometry'],
geometry='geometry')
Currently, I am running a for loop over these points and polygons to see which point falls within which polygon and returning there names and Ids to a list loc
like so:
loc = []
for geo1, name in zip(df['geometry'], df['name']):
for geo2, id in zip(points['geometry'], points['id']):
if geo1.contains(geo2):
loc.append([id, name])
Now what I want to try and do is alter the loop so it adds a column to the points dataframe called 'inside' and returns 'True' if the point is in a polygon and 'False' if it isn't.
I've tried:
points['inside'] = ''
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')
but it doesn't work
How can I best do this?
sorry if there is a very basic answer that I have missed.
Its been suggested below that this might be a duplicate of another question, however the one that is linked does not refer to adding the results to a column and whilst the Matplotlib methodology may be faster, when I run the example script provided I get the error float() argument must be a string or a number, not 'zip'
Upvotes: 1
Views: 273
Reputation: 5204
You are trying to append
to a string...
Just change the line points['inside'] = ''
to points['inside'] = []
points['inside'] = []
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')
This works for me...
Hope you find this helpful!
Upvotes: 1