QGIS Maximum Value Column – Returning Column Name of the Max Value in QGIS

attribute-tablefield-calculatorfields-attributesmaximumqgis

I am working with some age group data in QGIS based on point counts within a polygon grid and I would like to calculate the max value from a row with 11 different age groups in order to get the dominant age group within each grid cell.

The issue is I would like the returned value to be the column name as the value itself is meaningless.

Example of the data

So in row one it would be the max value or columns 7 to 17, returned as column name as the dominant age group for that cell… the value would be useful too as I might want to use percentages later.

Best Answer

Similar to @Matt's answer with using the "Function Editor", however, my suggestion is to work with the attributes() function.

Let's assume there is a layer called 'test' with its attribute table, see image below.

input_at

Open the field calculator (Ctrl + I) and proceed to the Function editor tab, where create a new function with the following content:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def maxvaluefieldname(attrmap, feature, parent):
    _attrmap = {key: attrmap[key] for key in attrmap.keys() if key not in ["fid"]} # exclude not needed fields
    return [k for k,v in _attrmap.items() if v==max(_attrmap.values())][0]

function_editor

switch to the Expression tab, paste the following expression maxvaluefieldname(attributes())

expression

and get the output:

result


The input:

test_data

The function:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def maxvaluefieldname(attrmap, feature, parent):
    _attrmap = {key: attrmap[key] for key in attrmap.keys() if key not in ["fid", "id", "left", "top", "right", "bottom", "Dom_age"] and attrmap[key] is not None} # exclude not needed fields
    return [k for k,v in _attrmap.items() if v==max(_attrmap.values())][0]

and the output:

test_data_result


References:

Related Question