Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/parabol123654>`_.


Documentation
Expand Down
5 changes: 4 additions & 1 deletion xarray/computation/nanops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
17 changes: 17 additions & 0 deletions xarray/tests/test_duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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_],
Expand Down
Loading