[GIS] QGIS field calculator expression: selecting min/max values within field groups

field-calculatorlineqgisvector

I am new to using QGIS (previously used Arc) and trying to get my head round the expressions and Python.

I have series of polylines representing routes and require the linear distance from the midpoint (along the polyline line) to the start (or end) point of the polyline.

So far I have been able to crack creating the points: I created the points using Qchainage pulgin and now have polylines at the start point, mid point and end point for each polyline. – see below the attributes of these points where "fid" relates back the polyline id and "cng_(meter" is the distance along the polyline created by Qchainage.

enter image description here

I have created a column to easily select only the start points ("START" column), by selecting only "0" values and now need to populate the "MID" column.

I now require selecting only the midpoint values. (A task similar to this thread in Arc Query to select MIN and MAX values by groups)

Obviously this is easily done in excel using the dbf, but I wish to challenge my skills in writing expressions for the calculator or in python.

Is there an easy way to do this?

I would then use the MMQGIS "Hub distance" to create linear polylines from the start point to the mid point. Does anyone have any other thoughts on this process too?

Best Answer

Well i want did the same but, i can´t find... this the way i solve it. Maybe can help to anybody

from qgis.core import *
import qgis.utils
canvas = qgis.utils.iface.mapCanvas();
layer = canvas.layer(1)

maxArea = 0
maxId = 0
selection =[]

uniquevalues = [];
dP= layer.dataProvider()
id = dP.fields().indexFromName('myColumn')
#i have the unique values from some column
uniquevalues = dP.uniqueValues( id )
#then i go for each value that is equal to my Unique value
for uv in uniquevalues:    
    exprec = QgsExpression( 'myColumn = ' + uv )
    exprec.prepare( layer.pendingFields() )
    for feature in layer.getFeatures():
        value = exprec.evaluate( feature )

        if bool( value ):
            #areaDegs is the column what i want get the max value
            if feature['areaDegs'] > maxArea :
                maxArea = feature['areaDegs'] 

                maxId = feature.id()
    #here i store de Id´s width de Max values and unique values from myColumn
    selection.append( maxId )
    maxId =0
    maxArea = 0
layer.setSelectedFeatures( selection )

Maybe there are a best way to do it, but for now, this is the way i do it.