code: def rolling_mean_by_h(x, h, w, name):
      """Compute a rolling mean of x, after first aggregating by h.
  
      Right-aligned. Computes a single mean for each unique value of h. Each
      mean is over at least w samples.
  
      Parameters
      ----------
      x: Array.
      h: Array of horizon for each value in x.
      w: Integer window size (number of elements).
      name: Name for metric in result dataframe
  
      Returns
      -------
      Dataframe with columns horizon and name, the rolling mean of x.
      """
      # Aggregate over h
      df = pd.DataFrame({"x": x, "h": h})
      df2 = (
          df.groupby("h")
          .agg(["sum", "count"])
          .reset_index()
          .sort_values("h")
      )
      xs = df2["x"]["sum"].values
      ns = df2["x"]["count"].values
      hs = df2.h.values
  
      trailing_i = len(df2) - 1
      x_sum = 0
      n_sum = 0
      # We don't know output size but it is bounded by len(df2)
      res_x = np.empty(len(df2))
  
      # Start from the right and work backwards
      for i in range(len(df2) - 1, -1, -1):
          x_sum += xs[i]
          n_sum += ns[i]
          while n_sum >= w:
              # Include points from the previous horizon. All of them if still
              # less than w, otherwise weight the mean by the difference
              excess_n = n_sum - w
              excess_x = excess_n * xs[i] / ns[i]
              res_x[trailing_i] = (x_sum - excess_x) / w
              x_sum -= xs[trailing_i]
              n_sum -= ns[trailing_i]
              trailing_i -= 1
  
      res_h = hs[(trailing_i + 1) :]
      res_x = res_x[(trailing_i + 1) :]
  
      return pd.DataFrame({"horizon": res_h, name: res_x})
  
imports: from __future__ import absolute_import, division, print_function
  import logging
  from tqdm.auto import tqdm
  from copy import deepcopy
  import concurrent.futures
  import numpy
  import pandas
label_desc: Use image node_id 6 for calling a global function with example usage: rolling_mean_by_h(x, h, w, name) and returns: pd