diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 7ad0a835c5c..ee9ff0411b7 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -26,6 +26,11 @@ Deprecations Bug Fixes ~~~~~~~~~ +- :py:meth:`DataArray.var` and :py:meth:`DataArray.std` (and the + :py:class:`Dataset` versions) on ``object`` arrays now give the right result when + reducing the last axis of a 2-D array, and ``std`` no longer raises when the data + contain missing values (:pull:`11987`). + By `Manh Nguyen `_. Documentation diff --git a/xarray/computation/nanops.py b/xarray/computation/nanops.py index 2ba20047326..fa3d7ceda43 100644 --- a/xarray/computation/nanops.py +++ b/xarray/computation/nanops.py @@ -109,7 +109,7 @@ def _nanmean_ddof_object(ddof, value, axis=None, dtype=None, **kwargs): ddof argument will be used in _nanvar method. """ - valid_count = count(value, axis=axis) + valid_count = count(value, axis=axis, keepdims=kwargs.get("keepdims", False)) value = fillna(value, 0) # As dtype inference is impossible for object dtype, we assume float # https://github.com/dask/dask/issues/3162 @@ -164,6 +164,9 @@ def nanvar(a, axis=None, dtype=None, out=None, ddof=0): def nanstd(a, axis=None, dtype=None, out=None, ddof=0): + if a.dtype.kind == "O": + return np.sqrt(_nanvar_object(a, axis=axis, dtype=dtype, ddof=ddof)) + with warnings.catch_warnings(): warnings.filterwarnings( "ignore", r"Degrees of freedom <= 0 for slice", category=RuntimeWarning diff --git a/xarray/core/duck_array_ops.py b/xarray/core/duck_array_ops.py index 6dce5974239..a9cee5b31e5 100644 --- a/xarray/core/duck_array_ops.py +++ b/xarray/core/duck_array_ops.py @@ -388,10 +388,10 @@ def array_notnull_equiv(arr1, arr2): return lazy_equiv -def count(data, axis=None): +def count(data, axis=None, keepdims=False): """Count the number of non-NA in this array along the given axis or axes.""" xp = get_array_namespace(data) - return xp.sum(xp.logical_not(isnull(data)), axis=axis) + return xp.sum(xp.logical_not(isnull(data)), axis=axis, keepdims=keepdims) def sum_where(data, axis=None, dtype=None, where=None): diff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py index 896eaa3ea8c..499c32caaf5 100644 --- a/xarray/tests/test_duck_array_ops.py +++ b/xarray/tests/test_duck_array_ops.py @@ -596,6 +596,23 @@ def test_min_max_object_propagates_nan(func, values) -> None: assert_identical(actual, expected) +@pytest.mark.parametrize("func", ["var", "std"]) +@pytest.mark.parametrize("dim", ["x", "y", None]) +@pytest.mark.parametrize("ddof", [0, 1]) +def test_var_std_object_matches_float( + func: str, dim: str | None, ddof: int, use_dask: bool +) -> None: + # reducing the last axis of a square object array broadcast the per-row + # mean against the wrong axis, and std raised on object arrays with NaN + values = np.array([[1.0, 2.0, 4.0], [10.0, np.nan, 3.0], [5.0, 6.0, 0.0]]) + da = DataArray(values.astype(object), dims=("x", "y")) + if use_dask: + da = da.chunk({"x": 2}) + actual = getattr(da, func)(dim, ddof=ddof) + expected = getattr(DataArray(values, dims=("x", "y")), func)(dim, ddof=ddof) + assert_allclose(actual, expected) + + def _reduce_params(): for dtype, use_dask, func, skipna in itertools.product( [float, int, np.float32, np.bool_],