Search code examples
vectorrowfielddifferencesubtraction

How to get the difference between two rows in a vector layer field


So the field is from a vector layer attribute table. What I want is to be able to have the result when each row value in the field named “Distance” subtracts from the previous one, I get a result which I can then use for other calculations. So essentially I want to be able to say: row 3 in column 4 minus row 2 in column 4 (same columns but different rows subtracting each other). My code is shown below:

   fn = ‘C:/PLUGINS1/sample/checking.shp’

   layer = iface.addVectorLayer(fn, ”, ‘ogr’)
   layer=iface.activeLayer()
   idx=layer.fields().indexFromName(‘Distance’)

   with edit(layer):
      for f in layer.getFeatures():
          dist1 = float(row[2], column [4]) # since row 1 contains the field name
          dist2 = float(row[3], column [4])
          final = abs(dist2 – dist1)

An error appears. Am stuck here.


Solution

  • This really works:

       fn = 'C:/PLUGINS1/sample/checking.shp'
       layer = iface.addVectorLayer(fn, '', 'ogr') # '' means empty layer name
      
       for i in range(0, 1):
           feat1 = layer.getFeature(i)
           ab = feat1[0] # this is the first column and first row value
       for i in range(0, 2):
           feat2 = layer.getFeature(i)
           dk = feat2[0] # this is the first column and second row value
           lenggok = (dk - ab) # Note this is the difference between both rows 
    
       print(lenggok)