4

After my previous question Weighted values of field in QGIS, I successfully adapted the following formula in Expression dialogue

"Value" / (sum("Value") / (count(CASE WHEN "Value" >= 1 THEN +1 END)))

In QGIS in the Attribute Table, there are many fields with values for which I count using this formula.

However, I don't want to repeat all long action and therefore I need to create a function in the Function editor. How can I implement this?

Taras
  • 32,823
  • 4
  • 66
  • 137

1 Answers1

3

Use the following function in the 'Function Editor'.

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

@qgsfunction(args='auto', group='Custom')

def calculate_values(value, feature, parent):
    layer = qgis.utils.iface.activeLayer()
    sum_values = sum(filter(None,[f['Value'] for f in layer.getFeatures()]))
    count_value = sum(1 for x in filter(None,[f['Value'] for f in layer.getFeatures()]))
    if value:
        return float(value)/sum_values/count_value
    else:
        return NULL

The result of the function will give a desired output.

result


References:

Taras
  • 32,823
  • 4
  • 66
  • 137