jat*_*ani 8 python topology r-tree python-3.x geopandas
大家好,我正在尝试将选区形状文件映射到议会选区。我有[两者]的形状文件。基本上,我必须将人口普查数据中地区级别给出的所有变量映射到议会选区级别。所以我正在关注 pycon talk。一切工作正常,但我在 get_intersection 函数中遇到错误。错误是
TopologicalError: The operation 'GEOSIntersection_r' could not be performed. Likely cause is invalidity of the geometry <shapely.geometry.polygon.Polygon object at 0x7f460250ce10>。
我尝试过使用 pygeos 和 rtree。有一些链接说问题出在 pygeos 中。所以,我使用了rtree。但没有用。请帮忙提前谢谢。
我尝试过的代码是
constituencies=gpd.GeoDataFrame.from_file('/content/AC_All_Final.shp')
districts=gpd.GeoDataFrame.from_file('/content/2001_Dist.shp')
districts['AREA'] = districts.geometry.area
constituencies['AREA'] = constituencies.geometry.area
merged = gpd.sjoin(districts, constituencies).reset_index().rename(
columns={'index': 'index_left'})
def get_intersection(row):
left_geom = districts['geometry'][row['index_left']]
right_geom = constituencies['geometry'][row['index_right']]
return left_geom.intersection(right_geom)
***Error is at this point***
merged['geometry'] = merged.apply(get_intersection, axis=1)
merged['AREA'] = merged.geometry.area
Run Code Online (Sandbox Code Playgroud)
Error trace is given below:
TopologyException: Input geom 1 is invalid: Ring Self-intersection at or near point 77.852561819157373 14.546596140487276 at 77.852561819157373 14.546596140487276
---------------------------------------------------------------------------
TopologicalError Traceback (most recent call last)
<ipython-input-17-8123669e025c> in <module>()
4 return left_geom.intersection(right_geom)
5
----> 6 merged['geometry'] = merged.apply(get_intersection, axis=1)
7 merged['AREA'] = merged.geometry.area
7 frames
/usr/local/lib/python3.6/dist-packages/shapely/topology.py in _check_topology(self, err, *geoms)
36 "The operation '%s' could not be performed. "
37 "Likely cause is invalidity of the geometry %s" % (
---> 38 self.fn.__name__, repr(geom)))
39 raise err
40
TopologicalError: The operation 'GEOSIntersection_r' could not be performed. Likely cause is invalidity of the geometry <shapely.geometry.polygon.Polygon object at 0x7f460250ce10>
Run Code Online (Sandbox Code Playgroud)
mar*_*eis 13
错误消息准确地告诉您发生了什么情况。您的某些几何图形无效,因此您必须在应用之前使它们有效。在大多数情况下有效的简单技巧是使用buffer(0).
merged['geometry'] = merged.buffer(0)
Run Code Online (Sandbox Code Playgroud)
由于问题与几何有效性有关并且是由 GEOS 提出的,因此无论您使用 shapely/rtree 后端还是 pygeos 都没有关系。
Her*_*ert 11
从shapely 1.8开始,会有一个make_valid方法
然而,目前 shapely 1.8 还不是 pypi 上的稳定版本,您需要安装一个不稳定的版本
pip3 install shapely==1.8a2
Run Code Online (Sandbox Code Playgroud)
然后你可以使形状有效
pip3 install shapely==1.8a2
Run Code Online (Sandbox Code Playgroud)
请注意,形状的类型可能会发生变化,例如从多边形变为多边形。
然而,我认为最好(1)正确避免无效的形状或(2)选择make_valid,因为它是由 shapely 团队建议的,而不是.buffer(0)解决方法。
| 归档时间: |
|
| 查看次数: |
10666 次 |
| 最近记录: |