如何在Python中使用Geopandas测试Point是否在Polygon/Multipolygon中? [英] How do I test if Point is in Polygon/Multipolygon with geopandas in Python?

查看:223
本文介绍了如何在Python中使用Geopandas测试Point是否在Polygon/Multipolygon中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网站上获得了美国各州的多边形数据 arcgis 而且我还有一个具有城市坐标的Excel文件.我已将坐标转换为几何数据(点).现在,我想测试这些积分是否在美国.两者都是dtype:geometry.我以为我可以轻松进行比较,但是当我使用自己的代码时,对于每个Point我都会得到错误的答案.即使美国有积分.

I have the Polygon data from the States from the USA from the website arcgis and I also have an excel file with coordinates of citys. I have converted the coordinates to geometry data (Points). Now I want to test if the Points are in the USA. Both are dtype: geometry. I thought with this I can easily compare, but when I use my code I get for every Point the answer false. Even if there are Points that are in the USA.

代码是:

import geopandas as gp
import pandas as pd
import xlsxwriter
import xlrd
from shapely.geometry import Point, Polygon

df1 = pd.read_excel('PATH')
gdf = gp.GeoDataFrame(df1, geometry= gp.points_from_xy(df1.longitude, df1.latitude))

US = gp.read_file('PATH')

print(gdf['geometry'].contains(US['geometry']))

有人知道我做错了吗?

推荐答案

包含当前在GeoPandas中以一对一的方式(而不是一对多的)工作.为此,请使用 sjoin .

contains in GeoPandas currently work on a pairwise basis 1-to-1, not 1-to-many. For this purpose, use sjoin.

points_within = gp.sjoin(gdf, US, op='within')

这将仅返回 US 中的那些点.另外,您可以过滤包含点的多边形.

That will return only those points within the US. Alternatively, you can filter polygons which contain points.

polygons_contains = gp.sjoin(US, gdf, op='contains')

这篇关于如何在Python中使用Geopandas测试Point是否在Polygon/Multipolygon中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆