Quick jinja2 question, ignore "0" when doing an average

I am using an average sensor to get the average current temperature of a floor.

Sometimes when I reboot HA (such as after an update), my sensors report “0” as a current temperate for a moment. I’d like to ignore their value in my average when they report 0 and only use it when they don’t.

I tried using an if statement, but it gets convoluted and I’m not certain this is the most clean or efficient way, as I think I’d need to go in a for loop to go through all of them and stick their value in a temporary variable of some kind?

{% if state_attr('climate.thermostat_chambre_des_maitres', 'current_temperature'), 0 -%} 
In this case ignore it
{%- else -%}
In this car use it
{{ state_attr('climate.thermostat_chambre_des_maitres', 'current_temperature')}}
{%- endif %}

Surely there’s a smarter way to go about this?

Post your actual template…

You can use reject() or rejectattr() filters to remove values, but the specific way to use them will depend on your template.

Here’s what I have so far:

{% set templist = [state_attr('climate.thermostat_chambre_des_maitres', 'current_temperature'),(state_attr('climate.thermostat_salle_de_bain', 'current_temperature')),(state_attr('climate.thermostat_chambre_megane', 'current_temperature')),(state_attr('climate.thermostat_cuisine', 'current_temperature'))] %}

{% for i in templist %}
{% endfor %}

This returns all 4 current temperatures as 0. I’d like to add them up, and divide by the number of non-zero items in the list.

This is where I’m somewhat stumped. I’m not sure I’m going about it the right way.

{% set clim_list = ['climate.thermostat_chambre_des_maitres', 'climate.thermostat_salle_de_bain',
'climate.thermostat_chambre_megane', 'climate.thermostat_cuisine'] %}
{{ expand(clim_list | select('has_value')) | map(attribute= 'attributes.current_temperature') 
| reject('eq', 0) | average(0) }}

You may be onto something, but right now this errors out as all 4 sensors are reading 0 at the moment:

ValueError: Template error: average got invalid input '(<generator object select_or_reject at 0x7f786faf80>,)' when rendering template '{% set clim_list = ['climate.thermostat_chambre_des_maitres', 'climate.thermostat_salle_de_bain',
'climate.thermostat_chambre_megane', 'climate.thermostat_cuisine'] %}
{{ expand(clim_list | select('has_value')) | map(attribute= 'attributes.current_temperature') 
| reject('eq', 0) | average }}' but no default was specified

Add a default to average. I have fixed it above.