#Weighted Average

1 messages · Page 1 of 1 (latest)

visual aurora
#

I am trying to create a weighted average, and so far, all my attempts have failed. Would really appreciate it if it's possible or not.

In my particular case, I have a list of dictionaries of the form:

{%- set data = [
      {'x': 2, 'w': 1},
      {'x': 6, 'w': 0.1},
      {'x': 1, 'w': 2},
    ] %}

And I need to compute the weighted average. Something like:

sum(d['x'] * d['w'] for d in data) / sum(d['w'] for d in data)

Though this snippet is more like Python code than the template allowed in Home Assistant.

I thought of trying to do pair-wise products, but there's no product function:

zip(data | map(attribute='x'), data | map(attribute='w'))
| map('product')
| sum

And while there is a log function, there's no exp function to get around the lack of product function... so I'm a bit at a loss and would appreciate some help 🙂

tribal dagger
#

Here's a way to do it

{%- set data = [
      {'x': 2, 'w': 1},
      {'x': 6, 'w': 0.1},
      {'x': 1, 'w': 2},
    ] %}
{% set ns = namespace(x_sum=0, w_sum=0) %}
{% for i in data %}
  {% set ns.x_sum = ns.x_sum + i.x * i.w %}
  {% set ns.w_sum = ns.w_sum + i.w %}
{% endfor %}
{{ ns.x_sum / ns.w_sum }}
visual aurora
#

Ah nice! I just stumbled on the namespace a couple of minutes ago 😅