HMEAN

This function computes the harmonic mean of positive numeric values in a 2D input range.

For values x_1, x_2, \ldots, x_n with x_i > 0, the harmonic mean is:

H = \frac{n}{\sum_{i=1}^{n} \frac{1}{x_i}}

The harmonic mean emphasizes smaller values and is commonly used for rates and ratios. Non-numeric entries are ignored, and at least one positive value is required.

Excel Usage

=HMEAN(data)
  • data (list[list], required): 2D array of positive numeric values. Non-numeric values are ignored.

Returns (float): Harmonic mean of the input data, or error message (str) if input is invalid.

Example 1: Harmonic mean of 2x2 matrix

Inputs:

data
1 2
3 4

Excel formula:

=HMEAN({1,2;3,4})

Expected output:

1.92

Example 2: Single column with multiple rows

Inputs:

data
2
4
8
16

Excel formula:

=HMEAN({2;4;8;16})

Expected output:

4.26667

Example 3: Non-numeric values are ignored

Inputs:

data
5 6
text 7

Excel formula:

=HMEAN({5,6;"text",7})

Expected output:

5.88785

Example 4: Harmonic mean of 3x2 matrix

Inputs:

data
10 20 30
40 50 60

Excel formula:

=HMEAN({10,20,30;40,50,60})

Expected output:

24.4898

Python Code

from scipy.stats import hmean as scipy_hmean

def hmean(data):
    """
    Calculates the harmonic mean of the input data, flattening the input and ignoring non-numeric values.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.hmean.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        data (list[list]): 2D array of positive numeric values. Non-numeric values are ignored.

    Returns:
        float: Harmonic mean of the input data, or error message (str) if input is invalid.
    """
    def to2d(x):
        return [[x]] if not isinstance(x, list) else x

    try:
      data = to2d(data)

      if not isinstance(data, list) or not all(isinstance(row, list) for row in data):
        return "Error: Invalid input: data must be a 2D list."

      flat = []
      for row in data:
        for item in row:
          try:
            val = float(item)
            if val > 0:
              flat.append(val)
          except (TypeError, ValueError):
            continue

      if not flat:
        return "Error: Input must contain at least one positive number."

      result = scipy_hmean(flat)
      return float(result)
    except Exception as e:
      return f"Error: {str(e)}"

Online Calculator

2D array of positive numeric values. Non-numeric values are ignored.