4

I am looking for a way to replace all "NULL"-Values throughout multiple rows/ all "NULL"-Values in an attribute table. The table is from a SHP-File (shapefile).

Is there any easy way? Right now I am selecting then by hand and replace them row by row which takes quite some time. I have already tried to look up a solution, however as I want to replace them in the whole table it seems to be not that easy.

NULL values

Taras
  • 32,823
  • 4
  • 66
  • 137
Corninski
  • 41
  • 2

2 Answers2

3

This should work with text and numeric fields. Backup your data first..

layer = QgsProject.instance().mapLayersByName('replacenulls_backup')[0]
fs = layer.fields()
d = {e:0 if f.isNumeric() else '0' for e,f in enumerate(fs)}

with edit(layer): for row in layer.getFeatures(): data = row.attributes() for i, val in enumerate(data): if val == NULL: data[i]=d[i] row.setAttributes(data) layer.updateFeature(row)

enter image description here

BERA
  • 72,339
  • 13
  • 72
  • 161
  • I had to replace fs=lyr.fields() with fs=layer.fields() but it did just what I needed. Very nice. As suggested have a backup since it changed the attributes in the layer instead of creating a new in memory layer or it gave me an AssertionError if I put the layer in an edit session before running. – John Nov 03 '20 at 15:45
  • @BERA, can you be so kind and criticize the code I wrote. Can you please give me a suggestion or a recommendation on how to make it better. Thank you. – Taras Nov 30 '20 at 09:24
  • 1
    I'm no expert on pyqgis. If it is working and is understandable it's good :). I thought assigning string fields with 0 and not '0' would cause errors but apparently not. You could replace the start/stop editing with a with edit(lines_null): – BERA Dec 01 '20 at 08:57
1

A solutions with no programming required.

Let's assume there is a polyline layer 'line' (blue) with its attribute table accordingly, see image below.

input

Deploy the "Refactor fields" geoalgorithm. Unfortunately it has a disadvantage, filling the 'Source expression' with a Conditional Function is still necessary, i.e.

if(condition,result_when_true,result_when_false)

refactor

and get the output

result

Taras
  • 32,823
  • 4
  • 66
  • 137