问题描述
大家好, 我正在尝试将区shapefile映射到装配选区。 我有Both的形状文件。基本上,我必须将人口普查数据中地区级别给定的所有变量映射到装配选区级别。 因此,我正在跟踪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
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>
解决方法
从 shapely 1.8 开始,会有一个 make_valid
方法
然而,目前 pypi 上的 1.8 还不是一个稳定的版本,你需要安装一个不稳定的版本
pip3 install shapely==1.8a2
然后你可以使形状有效
from shapely.validation import make_valid
valid_shape = make_valid(invalid_shape)
请注意,形状的类型可能会发生变化,例如从多边形变为多多边形。
但是,我认为最好 (1) 正确避免无效形状或 (2) 选择 make_valid
,因为它是由匀称的团队建议的,而不是 .buffer(0)
解决方法。
错误消息告诉您发生了什么。您的某些几何形状无效,因此在进行申请之前必须使它们有效。在大多数情况下有效的简单技巧是使用buffer(0)
。
merged['geometry'] = merged.buffer(0)
由于该问题与几何图形的有效性有关,并且是GEOS提出的,因此,无论您使用shape / rtree后端还是pygeos,都没有关系。