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?

3

Still in process... Found a problem with changing all fields, not only the first one. Works perfectly in Python Console but behaves strange in Function Editor.

The function that solves your issue probably looks as follows. You just need to insert it into the Function Editor.

P.S. And do not forget to change the number that defines the column where your values are stored, i.e. feat.attributes()[@number]

"""
Define new functions using @qgsfunction. feature and parent must always be the
last args. Use args=-1 to pass a list of values as arguments
"""

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()]))

    values_length= len(filter(None,[f['Value'] for f in layer.getFeatures()]))

    if not layer.isValid():
            raise Exception('Layer is not valid')

    features = layer.getFeatures()

    for feat in features:
        attr = feat.attributes()[1]

        if attr == NULL:
            continue

        else:
            return (float(attr)/sum_values/values_length)

Example

I do have a layer that stores point objects.

Point_layer

The result of the function will give a certain output. However, it still requires adjustments.

Output


References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.