Skip to content

Instantly share code, notes, and snippets.

@NathanW2
Created January 2, 2013 00:49
Show Gist options
  • Save NathanW2/4431348 to your computer and use it in GitHub Desktop.
Save NathanW2/4431348 to your computer and use it in GitHub Desktop.
Sum and list all neighbour features in pyqgis
from PyQt4.QtCore import *
name_field = 'NAME'
sum_field = 'POP_EST'
neighbors_field = 'Neighbors'
total_field = 'Sum'
layer = qgis.utils.iface.activeLayer()
provider = layer.dataProvider()
layer.startEditing()
neighbor_name_index = provider.fieldNameIndex(neighbors_field)
neighbor_sum_index = provider.fieldNameIndex(total_field)
if neighbor_name_index == -1 and neighbor_sum_index == -1:
provider.addAttributes( [QgsField(neighbors_field, QVariant.String),
QgsField(total_field, QVariant.Int)])
neighbor_name_index = provider.fieldNameIndex(neighbors_field)
neighbor_sum_index = provider.fieldNameIndex(total_field)
sum_index = provider.fieldNameIndex(sum_field)
name_index = provider.fieldNameIndex(name_field)
# Select all features along with their attributes
allAttrs = layer.pendingAllAttributesList()
layer.select(allAttrs)
# Build the spatial index for faster lookup.
index = QgsSpatialIndex()
map(index.insertFeature, layer)
layer.select(allAttrs)
# Loop each feature in the layer again and get only the features that are going to touch.
for feature in layer:
ids = index.intersects(feature.geometry().boundingBox())
neighbor_list = []
sum_of_neighbors = 0
for id in ids:
f = QgsFeature()
layer.featureAtId(id, f)
attrmap = f.attributeMap()
touches = f.geometry().touches(feature.geometry())
name = attrmap[name_index].toString()
if touches:
neighbor_list.append(unicode(name))
sum_of_neighbors += attrmap[sum_index].toInt()[0]
neighbor_string = ','.join(neighbor_list)
provider.changeAttributeValues({feature.id(): {neighbor_name_index: neighbor_string,
neighbor_sum_index: sum_of_neighbors}})
layer.commitChanges()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment