TransWikia.com

Creating new field based on other layers' attributes - "for" cycle error

Geographic Information Systems Asked by FedericaZ on March 9, 2021

I’d like to create a new field in vector layer A, based on attributes in vector layers B and C but PyQGIS returns a series of wrong numbers, particularly just the first feature value of the field C (I suppose the error is in the for cycle’s script/sequence). Could you help me?

featuresB=layerB.getFeatures() 
featuresA=layerA.getFeatures() 
featuresC=layerC.getFeatures()    
for fA in featuresA:
    for fC in featuresC:
         for fB in featuresB:
             if fA.geometry().area()*2>=fB.geometry().area():
                print fC[field_x]
             else:
                print fA[field_y]

One Answer

Assuming you have the same number of features in all three layers, something like this could work:

featuresA=layerA.getFeatures() 
featuresB=layerB.getFeatures() 
featuresC=layerC.getFeatures()    
for fA, fB, fC in zip(featuresA, featuresB, featuresC):
    if fA.geometry().area()*2 >= fB.geometry().area():
        print fC[field_x]
    else:
        print fA[field_y]

Answered by Tom Chadwin on March 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP