Daily mean of a sensor

Hi all.

I have a sensor returning a sequence of measurements (in more or less regular intervals) such as:

0 0 0 1 1 2 3 3 3 3 4 3 2 2 2 1 0 0 0 0 0 0 1 1 2 2 2 3 ...

and I want to have a “dynamic” mean value in the non-zero data points (i.e. zeros are ignored).
The mean should bee like (sum/count):
- - - 1 2/2 4/3 7/4 10/5 13/6 16/7 20/8 23/9 25/10 27/11 29/12 30/13 30/13 30/13 ... 30/13 31/14 32/15 34/16 36/17 38/18 41/19 ...

and this computed on a daily basis, meaning that the statistics will be cleared at 0:00.

I was able to make a template sensor filtering out the zero values (hopefully, it is not wrong):

   - sensor:
     - name: data_noZero
       state: >
              {% if states('sensor.data') | float(0) > 0 %}
                 {{ states('sensor.data') }}
              {% else %}
                 {{ this.state }}
              {% endif %}

But I don’t know how to make the rest of the computation.
Using:

   - platform: statistics
     name: "data_stats"
     entity_id: sensor.data_noZero
     state_characteristic: mean
     max_age:
       hours: 24

gives me value different than when computed manually.

How to solve this?

Thank you very much for any help,
DT

Hi all,
after some experimenting, it seems that this modification did the trick:

   - sensor:
     - name: data_noZero
       state: >
              {% if states('sensor.data') | float(0) > 0 %}
              {{    states('sensor.data') }}
              {% else %}
              {{    this.state }}
              {% endif %}
       attributes:
         last_changed: >
              {% if states('sensor.data') | float(0) > 0 %}
              {{    now() }}
              {% else %}
              {{    this.attributes.last_changed }}
              {% endif %}

I.e. it modifies state every time a non-zero value arrives. In this way, the sensor seems to propagate updates (due to attribute.last_changed change) even when the same values following each other are measured by sensor.data.

Still, it may be wrong. So I will appreciate a more correct solution anyway …

Thanks,
DT