2

I need to create new Field in Attribute table of vector layer, and afterwards to calculate values and store them in that Field for all features I have in that layer. I have solution which works, but thing is that it is too slow. Does anyone has an idea for faster way?

    # Dodavanje nove kolone
    name = "Vrednost" 
    provider = trecilayer.dataProvider()
    caps = provider.capabilities()
    # Provera da li kolona vec postoji, vraca "-1" ako ne postoji
    ind = provider.fieldNameIndex(name)
    try:
        if ind == -1:
            if caps & QgsVectorDataProvider.AddAttributes:
                res = provider.addAttributes( [ QgsField(name,QVariant.Double) ] )           
    except:
        return False
    #trecilayer.updateFields()

    # Zamisljam da sam koeficijente ucitao iz ulaznog fajla
    #koef=[1.00, 0.85, 0.80, 0.75, 0.70, 0.60, 0.50, 0.40, 0.00]
    lista=open(self.putanja,'r')
    lista.read
    for string in lista:
        x=string.split(",")
    koef=[]
    for i in range(len(x)):
        koef.append(float(x[i]))
    lista.close()



    #priprema za progress bar
    #ukupan broj redova 
    trecilayer.selectAll()
    count = trecilayer.selectedFeatureCount()
    i=0
    #racunanje vrednosti
    trecilayer.startEditing()
    for feature in trecilayer.getFeatures():
        QgsMessageLog.logMessage(str(trecilayer.fieldNameIndex('Vrednost')), 'Vrednost_Parcele')
        razred=feature['Procembeni']
        povrsina=feature.geometry().area()
        nova=povrsina*float(koef[int(razred-1)])
        feature['Vrednost'] = nova
        trecilayer.updateFeature(feature)
        #progress bar
        self.pb(i,count)
        i=i+1

    trecilayer.commitChanges()
1

You're making your updates feature by feature. I've found that making changes in bulk is orders of magnitude faster.

prepare your changes in the loop by making a dictionary of fids to change and the desired attribute changes. Then run the update outside the loop in a single step as per the Modify Features section of the pyQGIS cookbook Documentation QGIS testing: Using Vector Layers

You may be able to further speed up the code by running a select query to make the loop smaller as per the "Iterating over a subset of features" section

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.