Skip to content

Instantly share code, notes, and snippets.

@stekhn
Created September 19, 2023 15:03
Show Gist options
  • Save stekhn/8f7374b1608bf4be7c8dac20c22018d2 to your computer and use it in GitHub Desktop.
Save stekhn/8f7374b1608bf4be7c8dac20c22018d2 to your computer and use it in GitHub Desktop.
Add the names of all neighboring polygons as a new attribute to every polygon in layer (QGIS 3)
from qgis.utils import iface
from PyQt5.QtCore import QVariant
NAME_COLUMN = 'NAME'
NEIGHBORS_NAME_COLUMN = 'NEIGHBORS'
layer = iface.activeLayer()
layer.startEditing()
layer.dataProvider().addAttributes([QgsField(NEIGHBORS_NAME_COLUMN, QVariant.String)])
layer.updateFields()
feature_dict = {f.id(): f for f in layer.getFeatures()}
index = QgsSpatialIndex()
for f in feature_dict.values():
index.insertFeature(f)
for f in feature_dict.values():
print('Working on %s' % f[NAME_COLUMN])
geom = f.geometry()
intersecting_ids = index.intersects(geom.boundingBox())
neighbors = []
for intersecting_id in intersecting_ids:
intersecting_f = feature_dict[intersecting_id]
if (f != intersecting_f and
not intersecting_f.geometry().disjoint(geom)):
neighbors.append(intersecting_f[NAME_COLUMN])
f[NEIGHBORS_NAME_COLUMN] = ','.join(neighbors)
layer.updateFeature(f)
layer.commitChanges()
print('Processing complete.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment