0

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.

2
  • I added PyQGIS tag as it seems you want to do it this way - remove and clarify your question if otherwise (e.g. using the field calculator). By the way: if you create new fields, they stand for the attributes. By adding the attributes, you mean the values of these attributes?
    – Babel
    Jul 5 '21 at 9:23
  • Yes, I mean the values. I used to do using field calculator but in this project, I need to do with PyQGis. It is faster. Jul 5 '21 at 9:33
1

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}})
1
  • Thanks Ben, for 'LDC' field it works perfectly. However, for 'Fecha' I only need: Step 1; get first 10 digits (YYYY/MM/DD) and Step 2; replace("Fecha", '/',''). Fecha should be; Fecha = YYYYMMDD. Jul 5 '21 at 13:57

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.