Saturday, 20 August 2016

attribute table - Exploding features based on numerical field in QGIS?


I have a set of data as polygons, each with a Number field with value X. Is there then a way to copy this into X number of polys at the same location? (ideally points distributed across the poly but that's a bonus).


In QGIS I have tried Random Points, but this doesn't inherit attributes, and Join Attributes by Location is useless if the parent polys overlap.



The reason behind this is for collating data easily with the GroupStats plugin.



Answer



It's quite easy to do with a small python script. You can paste the following snippet to the python console. To initialize the layer variable you can select it in the TOC and run layer = iface.activeLayer() befor running the code.


layer.startEditing()
for f in layer.getFeatures():
# Create X-1 new features since we already have the original
for i in range(f['X']-1):
layer.addFeature(f)
layer.commitChanges()


Or to write it to another layer (make sure it has the same attributes and geometry type!):


ltarget.startEditing()
for f in lsource.getFeatures():
for i in range(f['X']):
ltarget.addFeature(f)
ltarget.commitChanges()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...