i'd like to duplicate/triple a geometry based on a numeric field in the attribute table. For example, if there is number 2 corresponding to a record, needs to duplicate this gemometry; if there is number 3, needs to triple this geometry and so on..

Any suggestions, tools or plug-in to do this?

  • 1
    When you duplicate the geometry, do you intend to keep it as a multipart geometry in the original record (not adding any rows to the table), or are you duplicating the records (adding additional rows for each duplicated geometry)? Either one can be easily accomplished with POSTGIS. – jbalk Dec 9 '19 at 23:54
  • Thanks for the tip about Postgis data. – Mark Jan 7 at 20:07

I'll give you an example, you can adapt it to your case and optimize it.

My starting table with 2 fields: the first one an identifier and the second the numerical value corresponding to the number of duplicates.

enter image description here

The code I execute in QGIS python console

layer = iface.activeLayer() # my layer 
provider = layer.dataProvider() # access to the features of the layer 

# Loop on the features of the layer 
for feature in layer.getFeatures():
    id_duplicate = feature["id"] # value of the field id 
    number_duplicate = feature["number"] # number of duplicates
    geometry_duplicate = feature.geometry() # geometry of my feature

# initialization of my counter which will allow me to know when I should stop duplicating 
counter = 0
while counter != number_duplicate :
    new_feature = QgsFeature() # new feature 
    new_feature.setAttributes([id_duplicate,number_duplicate]) # I apply the same attributes 
    new_feature.setGeometry(QgsGeometry(geometry_duplicate)) # I apply the same geometry
    provider.addFeature(new_feature) # Addition of the new entity 

    counter += 1
    # if the value of my field is equal to 1 then I stop duplicating this entity 
    and move on to the next one otherwise I continue.

My end table

My end table

Feel free to ask for more information if you don't understand the code. If you want a multigeometry and do not duplicate the lines, you can use the dissolved tool with the grouping field "id".

| improve this answer | |
  • Thanks for the information! But, if i'd like to have 1 record when there is 1 in the "id" field, 2 records when there is 2 and so on? – Mark Jan 7 at 20:05
  • @Marco in Vincent's code you can change 'counter = 0' to 'counter = number_duplicate - 1' then change 'while counter != number_duplicate:' to 'while counter > 0:' and finally change 'counter += 1' to 'counter -= 1'. You'll need to test it but it should work that way. – jbalk Jan 7 at 21:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.