Hello together! I have already read a post on how to calculate the mean, but I would like to do it a little differently.
Namely, it is about calculating the correct average value when a sensor is no longer accessible (battery empty). So the denominator would have to vary.
You can use filters to remove the entities you do not want to include before taking the average. The average filter will automatically base the denominator of its calculation on how many entities are left in the list.
{{ states.sensor
| rejectattr('attributes.device_class','undefined')
| selectattr('attributes.device_class','eq', 'battery')
| map(attribute='state')
| select('is_number')
| map('int')
| list | average }}
If you also want to exclude batteries that return a value of 0, you can add | reject('eq', 0) after the map('int') filter.
I would find it wiser to include a few sensors and not have to think about this automation when I later add more sensors of the same type to home assistant.
I don’t understand your comment… the template starts with states.sensor which means you are starting out with every entity in thesensor domain.
Because the filters act sequentially. When you use reject, you are removing that entity from the list, then the next reject removes one more… and so on.
{% set l = ['a', 'b', 'c', 'd', 'e'] %}
{{ l | reject('eq','a') | list }}
> returns: ['b', 'c', 'd', 'e']
{{ l | reject('eq','a')| reject('eq','b') | list }}
> returns: ['c', 'd', 'e']
But when you use select, you are removing all the entities from the list except the one you have specified. Then the second select removes everything but your second selection, which includes the one thing left in the list… leaving you with an empty list. As the error message explains, the average filter can’t take the average of nothing.
{% set l = ['a', 'b', 'c', 'd', 'e'] %}
{{ l | select('eq','a') | list }}
> returns: ['a']
{{ l | select('eq','a') | select('eq','b') | list }}
> returns: []
that’s because im new to HA and I still have to find my way around with the templates
i had to move 130 automations to home assistant after 6 years of pimatic and honestly did not have the patience to read into the details. thank you for your explanation. helped