I have a polygon shapefile and I need to generate n new fields reporting the n largest values across k variables. In this particular case n = 3, so that I would like to create three new fields: "max_area_1"
, "max_area_2"
, "max_area_3"
, with the highest, the second and third largest, values across variables x1, x2, ..., xk
.
To make things clearer, consider this simpliefied version of my data:
x1 x2 x3 x4
10 31 73 14
7 69 55 2
91 9 87 13
What I would like to get is:
x1 x2 x3 x4 max_area_1 max_area_2 max_area_3
10 31 73 14 73 31 14
7 69 55 2 69 55 7
91 9 87 13 91 87 13
Using the field calculator in Python console of QGIS, I can compute the highest value using the max function. My code is:
crops = [x1, ..., xk]
processing.run("qgis:fieldcalculator", {
"INPUT": input_layer,
"FIELD_NAME": "max_area_1",
"FIELD_TYPE": 0,
"NEW_FIELD": True,
"FORMULA": 'max(crops)',
"OUTPUT": output_layer})
Any idea on how I can compute, in PyQGIS, three new fields reporting the three largest values across the relevant variables?