TransWikia.com

Adding column with area values in attributes table with standalone PyQGIS

Geographic Information Systems Asked on June 25, 2021

I would like to add an area column to the Attributes table using Python. I prefer not to use QGIS Python console. I would like to do that using cmd. How should I change my code?

My code and error below:

  import sys, os
  sys.path.append(r'C:/PROGRA~1/QGIS3~1.16/apps/qgis/python/plugins')
  os.environ['PROJ_LIB'] = 'C:Program FilesQGIS 3.16shareproj'
    
  from qgis.core import *
  from qgis.utils import *
  from qgis.analysis import QgsNativeAlgorithms
  from qgis.core import QVariant
    
  qgispath = r'C:/PROGRA~1/QGIS3~1.16/apps/qgis'
     
  QgsApplication.setPrefixPath(qgispath, True)
  qgs = QgsApplication([], False)
  qgs.initQgis()
    
  import processing
  from processing.core.Processing import Processing
    
  Processing.initialize()
  QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
  feedback = QgsProcessingFeedback()
    
  processing.run("native:joinattributesbylocation", {'INPUT':r'C:/Users/ja/Inne/Desktop/malebudynki.shp|layername=malebudynki',
                                                     'JOIN':r'C:/Users/ja/Inne/Desktop/adresy/adresyzukladem.shp',
                                                     'PREDICATE':[1,5],
                                                     'JOIN_FIELDS':['PNA','SIMC_id','SIMC_nazwa','ULIC_nazwa','Numer'],
                                                     'METHOD':0,
                                                     'DISCARD_NONMATCHING':True,
                                                     'PREFIX':'',
                                                     'OUTPUT':r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'})
    
  #add area column to attributes table
  layer = r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'
  provider = layer.dataProvider()
  area_field = QgsField("Area", QVariant.Int)
  provider.addAttributes([area_field])
  layer.updateFields()
    
  idx = provider.fieldNameIndex('Area')
  for feature in layer.getFeatures():
      attrs = {idx : int(feature.geometry().area())}
      layer.dataProvider().changeAttributeValues({feature.id() : attrs})

>>> #add area column to attributes table
... layer = r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'

>>> provider = layer.dataProvider()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'dataProvider'
>>> area_field = QgsField("Area", QVariant.Int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'QVariant' is not defined
>>> provider.addAttributes([area_field])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'provider' is not defined
>>> layer.updateFields()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'updateFields'
>>> idx = provider.fieldNameIndex('Area')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'provider' is not defined
>>> for feature in layer.getFeatures():
    ... attrs = {idx : int(feature.geometry().area())}
    ... layer.dataProvider().changeAttributeValues({feature.id() : attrs})

One Answer

You can execute the following code in the Python Console of QGIS.

from PyQt5.QtCore import QVariant

# Step 1 : Adding the Area field
layer = QgsVectorLayer("C:/Users/ja/Inne/Desktop/treningowawarstwa.shp", "your_layer", "ogr")
provider = layer.dataProvider()
area_field = QgsField("Area", QVariant.Int)
provider.addAttributes([area_field])
layer.updateFields()


# Step 2 : Updating the Area field for each feature
idx = provider.fieldNameIndex('Area')
for feature in layer.getFeatures():
    attrs = {idx : int(feature.geometry().area())}
    layer.dataProvider().changeAttributeValues({feature.id() : attrs})

Correct answer by Vincent Bré on June 25, 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