pandas geopandas 指向多边形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48097742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:00:52  来源:igfitidea点击:

geopandas point in polygon

pythonpandasgeopandaspoint-in-polygon

提问by Kvothe

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

我有一个多边形的 GeoDataFrame (~30) 和一个点的 GeoDataFrame (~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.

如果点存在于多边形中,我希望在我的点的 GeoDataFrame 中创建 30 个新列(具有适当的多边形名称),并使用简单的布尔值 True/False。

As an example, the GeoDataFrame of Polygons is this:

例如,多边形的 GeoDataFrame 是这样的:

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:

Points 的 GeoDataFrame 是这样的:

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!

但鉴于我有 30 个多边形,我想知道是否有更好的方法。感谢任何帮助!

回答by Paul H

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:

不太清楚你实际拥有什么样的数据结构。此外,您所有的预期结果都是 False,因此很难检查。假设 GeoSeries 和 GeoDataFrames,我会这样做:

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