MOMENT
Overview
The MOMENT
function calculates the nth moment about the mean for a sample. Moments are quantitative measures related to the shape of a data set’s distribution. The first moment is the mean, the second is the variance, the third is skewness, and the fourth is kurtosis. This function flattens the input data, ignores non-numeric values, and does not support axis or nan_policy arguments, unlike scipy.stats.moment
. For more details, see the scipy.stats.moment documentation .
This example function is provided as-is without any representation of accuracy.
Usage
To use the function in Excel:
=MOMENT(data, moment)
data
(2D list, required): The input data as a 2D list (column or matrix). Non-numeric values are ignored.moment
(float, required): The order of the moment to calculate (must be a positive integer).
The function returns a single value (float): the nth moment about the mean of the data, or an error message (string) if the input is invalid.
Examples
Example 1: Second Moment (Variance) of a Column Vector
Inputs:
data | moment |
---|---|
1 | 2 |
2 | |
3 | |
4 | |
5 |
Excel formula:
=MOMENT({1;2;3;4;5}, 2)
Expected output:
Result |
---|
2.0 |
Example 2: Third Moment (Skewness) of a Row Vector
Inputs:
data | moment | ||||
---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 3 |
Excel formula:
=MOMENT({1,2,3,4,5}, 3)
Expected output:
Result |
---|
0.0 |
Example 3: Fourth Moment (Kurtosis) of a Matrix
Inputs:
data | moment | ||
---|---|---|---|
1 | 2 | 3 | 4 |
4 | 5 | 6 |
Excel formula:
=MOMENT({1,2,3;4,5,6}, 4)
Expected output:
Result |
---|
14.7292 |
Example 4: First Moment (Mean) of a Column Vector
Inputs:
data | moment |
---|---|
10 | 1 |
20 | |
30 |
Excel formula:
=MOMENT({10;20;30}, 1)
Expected output:
Result |
---|
0.0 |
Python Code
from scipy.stats import moment as scipy_moment
import numpy as np
def moment(data, moment):
"""
Calculates the nth moment about the mean for a sample.
This function flattens the input data, ignores non-numeric values, and does not support axis or nan_policy arguments, unlike scipy.stats.moment.
This example function is provided as-is without any representation of accuracy.
Args:
data: 2D list of values (column, row, or matrix). Non-numeric values are ignored.
moment: Order of the moment (positive integer).
Returns:
The nth moment about the mean (float), or an error message (str) if invalid input.
"""
# Flatten and filter numeric values
try:
arr = np.array(data, dtype=object).flatten()
arr = [float(x) for x in arr if x is not None and str(x).strip() != '' and np.isfinite(float(x))]
except Exception:
return "Two or more data elements are needed"
if not isinstance(moment, (int, float)) or int(moment) != moment or moment < 1:
return "Moment must be a positive integer"
if len(arr) < 2:
return "Two or more data elements are needed"
try:
result = scipy_moment(arr, moment=int(moment), axis=None, nan_policy='omit')
return float(result)
except Exception:
return "Error computing moment"