Python - 从与 Polygon 相交的 MultiLineString shapefile 中包含的 Line 获取属性

Python - Getting attributes from Line contained in a MultiLineString shapefile that intersects a Polygon

我有 2 个 shapefile,其中 1 个包含许多构成道路网络的线,另一个包含许多 GPS 点。

到目前为止,我已经成功地打开了两个 shapefile 并使用 Shapely 和 Fiona 执行了一个 intersection(),使用此处找到的代码 - https://gis.stackexchange.com/a/128210/52590

这是我获取交点的代码副本:

from shapely.geometry import shape, MultiLineString
import fiona

Multilines = MultiLineString([shape(line['geometry']) for line in fiona.open("shapefiles/edges.shp")])
Poly = shape(fiona.open("shapefiles/testBuffer.shp").next()['geometry'])
intersecciones = Multilines.intersection(Poly)

这就是 'intersecciones' 打印时的样子:

> MULTILINESTRING ((339395.1489003573 6295646.564306445,
> 339510.1820952367 6295721.782758819), (339391.2927481248 6295686.99659219, 339410.0625 6295699), (339404.4651918385 6295630.405294137, 339520.18020253 6295708.663279793))

所以这意味着线 shapefile 和多边形 shapefile 的第一个多边形之间有 3 个交点。

我需要的是从与多边形相交的线形文件中的每一行获取两个属性('Nombre' 和 'Sentido'),以及它们相交的确切点,所以我可以得到从多边形中心到交点后的距离。

所以我的问题是是否有任何方法可以使用 Shapely 或现有的任何其他 Python 库来获取这些属性。另外,遍历每个多边形并保存数据的最佳方法是什么?我在想可能是一个字典,其中包含每个多边形,这些多边形具有相交线和距离的属性。最后,有没有更有效的方法来找到交叉点?处理一个多边形大约需要 1 分钟,以后我可能需要它更快。

如果我遗漏了任何信息,请告诉我,以便我可以编辑问题。

非常感谢您, 费利佩.

你应该看看 GeoPandas http://geopandas.org/ which uses Fiona and Shapely whilst giving you also direct access to the attributes in a nice tabular format. Together with some pandas operations (such as in this post) 你应该能够用几行代码做你想做的事。

可能不是最好的代码,但我通过加载点 shapefile(点属性所在的位置)、线 shapefile(线属性所在的位置)和多边形(缓冲点)解决了这个问题。然后我使用 2 'for' 检查每个缓冲点是否与每条线相交。如果是这样,我将使用完全相同的 'for'.

检索属性

最后我有 "listaCalles",这是一个包含多边形与线的每个交点的列表,具有许多属性。

red = fiona.open("shapefiles/miniRedVial.shp")  # loads road network
puntos = fiona.open("shapefiles/datosgps.shp")  # loads points

# open points with shapely and fiona
Multipoints = MultiPoint([shape(point['geometry']) for point in fiona.open("shapefiles/datosgps.shp")])
# open road network with shapely and fiona
Multilines = MultiLineString([shape(line['geometry']) for line in fiona.open("shapefiles/miniRedVial.shp")])
# open buffered points with shapely and fiona
Polygons = MultiLineString([list(shape(pol['geometry']).exterior.coords) for pol in fiona.open("shapefiles/testBuffer.shp")])

# create list where I'll save the intersections
listaCalles = []

for i in range(0, len(Polygons)):
    for j in range(0, len(Multilines)):
        if Polygons[i].intersection(Multilines[j]):
            idPunto = puntos[i].get("id")
            latPunto = puntos[i].get("properties").get("LATITUDE")
            lonPunto = puntos[i].get("properties").get("LONGITUDE")
            idCalle = red[j].get("id")
            nombreCalle = red[j].get("properties").get("NOMBRE")
            distPuntoCalle = Multilines[j].distance(Multipoints[i])
            listaCalles.append((idPunto, latPunto, lonPunto, idCalle, nombreCalle, distPuntoCalle))