[GIS] How to select and change only certain (same)values in attributetable in QGIS

attribute-tableqgis

I have an attributetable. Spread all over it are numbers like -99999997. I want to replace them by zero (0). There a many columns in which there are such numbers.
I have used the expression (an example with one column P-Ant_ARU)

case when   "P_ANT_ARU"  is  -99999997  then '0' else    "P_ANT_ARU"  end

for every feature in the column but I wonder if there is a faster way to use in the field calculator to get rid of all the -99999997 in one or perhaps two steps, because there are a lot of columns 🙂

I have also tried toint(0) but that doesn't work because you have to choose a field, and I want a value to be changed. The same problem occurs with the plugin QuickMultiAttributeEdit.

So how can I select all those numbers in the whole table and make them zero.

attributetable

Best Answer

Below are a couple of methods you could use in the Python Console which replaces all values in the Attribute Table of -99999997 with 0. As they are within a function, there shouldn't be anything printed in the console (incase this somehow freezes QGIS). After only limited testing, I found that changing attributes on a column by column basis was a bit faster.

  • Row by row:

    def by_row():
        layer = qgis.utils.iface.activeLayer()  
        layer.startEditing()   
        for feat in layer.getFeatures():
            f = feat.fields()
            num = f.count()
            for i in range(num):
                if feat[i] == '-99999997':
                    feat[i] = '0'
                    layer.updateFeature(feat)
        layer.commitChanges()
    
    by_row()
    
  • Column by column:

    def by_column():
        layer = qgis.utils.iface.activeLayer()  
        layer.startEditing()   
        for field in layer.dataProvider().attributeIndexes():
            for feature in layer.getFeatures():
                attrs = feature.attributes()
                if attrs[field] == '-99999997':
                    feature[field] = '0'
                    layer.updateFeature(feature)
        layer.commitChanges()
    
    by_column()
    
Related Question