TransWikia.com

Last record in the program in PyQGIS is not executed properly

Geographic Information Systems Asked by Karan Gupta on January 4, 2021

layer = vlayer4

provider = layer.dataProvider()

areas = [ feat.geometry().area() 
          for feat in layer.getFeatures() ]

field = QgsField("area", QVariant.Double)
provider.addAttributes([field])
layer.updateFields()

idx = layer.fieldNameIndex('area')

for area in areas:
    new_values = {idx : float(area)}
    provider.changeAttributeValues({areas.index(area):new_values})

This program runs properly and gives the desired results. However, it fails to execute to calculate the area of the last feature in the polygon shapefile. I have a polygon shapefile with 516 features. It rightly calculates the area of 515 features but terminates there and don’t give the area of 516th feature.

One Answer

Iterate over features instead of areas to add area value to a new field. As @BERA states in his comment, it must be two features which have the same area.

Use like this:

provider = layer.dataProvider()

field = QgsField("area", QVariant.Double)
provider.addAttributes([field])
layer.updateFields()

idx = provider.fieldNameIndex('area')

# iteration over features
for feat in layer.getFeatures():
    provider.changeAttributeValues({feat.id(): {idx: feat.geometry().area()} })

Answered by Kadir Şahbaz on January 4, 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