2

I am trying to populate an attribute table of a feature with attributes from another feature. I have been able to segregate the input data into fields named "From", "Eastings" and "Northings". I find this is not such a difficult task to carry out as this code helped. The problem now is the input data has only four(4) rows but when I run my script, it multiplies the number of rows and I end up with twenty rows. I am quite sure I need to change something in the code, i am not sure where as I am relatively new to python.

here is my code:

pr.addAttributes([QgsField('FROM',  QVariant.String)])
vpr.addAttributes([QgsField('Eastings',  QVariant.Double)])
vpr.addAttributes([QgsField('Northings',QVariant.Double)])
vlayer.updateFields()

vlayer.startEditing()
for things in vlayer.getFeatures():
    for i in new_attribs:
        things['FROM'] = i[0] 
        things['Eastings'] = i[1]
        things['Northings']=i[2]
        things.setAttributes(i[0])
        vpr.addFeatures([things])
           
        vlayer.updateFeature(things)

    vlayer.commitChanges()

This is the result I get:

enter image description here

How do I get only the four(4) rows I need?

3
  • 1
    What is new_attribs
    – BERA
    Mar 20, 2021 at 12:49
  • new_attribs is the attributes i need to populate the layer with.
    – GeomaSmart
    Mar 21, 2021 at 6:46
  • vlayer already as 4 features at the begining but no attributes ? Is new_attribs a list of lists ? Like this : new_attribs = [["SGC A562 16 1", 1099307.4, 307285.64], ["SGC A562 16 2", 1099349.96, 307243.6], ["SGC A562 16 3", 1099249.74, 307139.4], ["SGC A562 16 4", 1099203.19, 307170.55]] if vlayer already as features I don't understand why you add more with vpr.addFeatures([things])
    – JULESG
    Mar 23, 2021 at 10:52

1 Answer 1

1

You need at least to change the code to the following. The main change has been desindenting vpr.addFeatures([things]) to avoid adding unwanted "garbage" features. I'm also surprised why you edit the vlayer if you want to add your feature to vpr?

pr.addAttributes([QgsField('FROM',  QVariant.String)])
vpr.addAttributes([QgsField('Eastings',  QVariant.Double)])
vpr.addAttributes([QgsField('Northings',QVariant.Double)])
vlayer.updateFields()

vlayer.startEditing()
for things in vlayer.getFeatures():
    for i in new_attribs:
        things['FROM'] = i[0] 
        things['Eastings'] = i[1]
        things['Northings'] = i[2]
        things.setAttributes(i[0])
    vpr.addFeatures([things])
    vlayer.updateFeature(things)

    vlayer.commitChanges()

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.