TransWikia.com

Adding values into new fields with PyQGIS

Geographic Information Systems Asked by Juanjo Valero on July 16, 2021

I have created two new fields into a shp table but I do not know how to add the atributes using PyQGis. I used to do from field calculator but in this case I need it to do using PyQGis.

Step 1; Adding fields, works properly:

 Load a vector layer
#
## fn = 'c:/path/to/shapefile.shp'
# Path/nombre shp. En este caso solo el nombre
fn = 'C:/Users/juavafer/Proyectos/Costas_CoastSat/Output/Holanda/Shp/FromGeojson/Zona_Sur/Auto/Holanda_Sur_12_S2_ldcRef_Auto.shp'

layer = iface.addVectorLayer(fn, '', 'ogr')

# Get layer capabilities
#
caps = layer.dataProvider().capabilities()

# Add Fields
#
if caps & QgsVectorDataProvider.AddAttributes:
    res = layer.dataProvider().addAttributes([QgsField('Fecha', QVariant.String, "string",10),
    QgsField('LDC', QVariant.String,"string",25)])
    layer.updateFields()
  

Step 2; Add values into ‘Fecha’ and ‘LDC’, DO NOT WORK:

-LDC = Ref_Auto
-Fecha;

  1. Fecha = attribute( ‘date’)
  2. Fecha = replace("Fecha", ‘/’,”)

Where ‘date’ is an existing field in the attribute table. So, finally Fecha = YYYYMMDD.

I am trying with several posts with no results:

    https://www.geodose.com/2018/09/qgis-python-tutorial-add-field-attribute.html
    https://gis.stackexchange.com/questions/249555/adding-attributes-to-a-new-layer-in-pyqgis

Note: In this case each shp only has 1 row but others cases has many.

One Answer

It looks like you are trying to use field calculator syntax mixed with Python code.

I have updated your code below with an example of updating attribute values using the changeAttributeValues() method of QgsVectorDataProvider. The only thing is that I have no idea how you are trying populate the LDC field because I can't work out what "Ref_Auto -Fecha;" means. See my comments in the script below.

The essence of this method is that changeAttributeValues() takes a dictionary argument where the key is the feature id and the value is a second dictionary with field indexes as keys and the new attribute contents as values.

You can find out more here:

https://docs.qgis.org/3.16/en/docs/pyqgis_developer_cookbook/vector.html#modify-features

Try the snippet below:

fn = 'C:/Users/juavafer/Proyectos/Costas_CoastSat/Output/Holanda/Shp/FromGeojson/Zona_Sur/Auto/Holanda_Sur_12_S2_ldcRef_Auto.shp'

layer = iface.addVectorLayer(fn, '', 'ogr')

# Get layer capabilities
caps = layer.dataProvider().capabilities()

# Add Fields
if caps & QgsVectorDataProvider.AddAttributes:
    res = layer.dataProvider().addAttributes([QgsField('Fecha', QVariant.String, "string",10),
    QgsField('LDC', QVariant.String,"string",25)])
    layer.updateFields()

#Get indexes of LDC and Fecha fields
fecha_idx = layer.fields().lookupField('Fecha')
ldc_idx = layer.fields().lookupField('LDC')

# Change attribute values
for f in layer.getFeatures():
    fecha = f['date'].replace('/', '')
    ldc = 'desired LDC field value' # replace this (I can't work out what you want here from your code!)
    layer.dataProvider().changeAttributeValues({f.id(): {fecha_idx: fecha, ldc_idx: ldc}})

Correct answer by Ben W on July 16, 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