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:
How do I get only the four(4) rows I need?
1 Answer 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()
new_attribs
vlayer
already as 4 features at the begining but no attributes ? Isnew_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]]
ifvlayer
already as features I don't understand why you add more withvpr.addFeatures([things])