Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

python - geopandas point in polygon

I have a GeoDataFrame of polygons (~30) and a GeoDataFrame of Points (~10k)

I'm looking to create 30 new columns (with appropriate polygon names) in my GeoDataFrame of Points with a simple boolean True/False if the point is present in the polygon.

As an example, the GeoDataFrame of Polygons is this:

id  geometry
foo POLYGON ((-0.18353,51.51022, -0.18421,51.50767, -0.18253,51.50744, -0.1794,51.50914))
bar POLYGON ((-0.17003,51.50739, -0.16904,51.50604, -0.16488,51.50615, -0.1613,51.5091))

The GeoDataFrame of Points is like this:

counter     points
   1     ((-0.17987,51.50974))
   2     ((-0.16507,51.50925))

Expected output:

counter          points        foo    bar
   1    ((-0.17987,51.50974))  False  False
   1    ((-0.16507,51.50925))  False  False

I can do this manually by:

foo = df_poly.loc[df_poly.id=='foo']
df_points['foo'] = df_points['points'].map(lambda x: True if foo.contains(x).any()==True else False

But given that I have 30 polygons, I was wondering if there is a better way. Appreciate any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not really clear what kind of data structures you actually have. Also, all your expected results are False, so that's kind of hard to check. Assuming GeoSeries and GeoDataFrames, I would do this:

from shapely.geometry import Point, Polygon
import geopandas

polys = geopandas.GeoSeries({
    'foo': Polygon([(5, 5), (5, 13), (13, 13), (13, 5)]),
    'bar': Polygon([(10, 10), (10, 15), (15, 15), (15, 10)]),
})

_pnts = [Point(3, 3), Point(8, 8), Point(11, 11)]
pnts = geopandas.GeoDataFrame(geometry=_pnts, index=['A', 'B', 'C'])
pnts = pnts.assign(**{key: pnts.within(geom) for key, geom in polys.items()})

print(pnts)

And that gives me:

        geometry    bar    foo
A    POINT (3 3)  False  False
B    POINT (8 8)  False   True
C  POINT (11 11)   True   True

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...