Skip to content

Fix var and std on object arrays - #11987

Open
parabol123654 wants to merge 1 commit into
pydata:mainfrom
parabol123654:fix-object-var-std
Open

parabol123654 wants to merge 1 commit into
pydata:mainfrom
parabol123654:fix-object-var-std

Conversation

@parabol123654

Copy link
Copy Markdown

Description

var on an object array gives wrong numbers when reducing the last axis of a 2-D array: for [[1, 2], [10, nan]] as object, var("x") returns [0.625, 25.] instead of [0.25, 0.] (and a non-square array raises a broadcasting error). _nanmean_ddof_object is called with keepdims=True from _nanvar_object, but the valid count was computed without it, so the division broadcast against the wrong axis. I pass keepdims through to count.

std on object arrays with NaN raised TypeError (no callable sqrt) since it went straight to np.nanstd; it now takes the square root of the object variance, like nanvar already does for object dtype.

The new test compares object and float results for both reductions, every dim and ddof 0/1, with numpy and dask; 14 of the 24 cases fail on main. test_duck_array_ops, test_dataarray, test_dataset, test_rolling, test_weighted and test_groupby pass.

Checklist

  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: Claude Code. It found the bug while comparing object and float reductions and wrote the fix and test; I reproduced it, read the change and reran the tests myself.

[This is Claude Code on behalf of Manh Nguyen]

For object dtype, var goes through _nanvar_object, which computes the
mean with keepdims=True so it can be subtracted from the data. But
_nanmean_ddof_object only passed keepdims to the sum, not to the count
of valid values, so the sum (kept dims) was divided by a count without
them. Reducing the last axis of a 2-D array then broadcast wrongly:

    v = np.array([[1, 2], [10, np.nan]], dtype=object)
    xr.DataArray(v, dims=("y", "x")).var("x")  # [0.625, 25.], not [0.25, 0.]

and with a non-square array it raised a broadcasting ValueError. This
goes back to the nanops refactor in pydata#2236.

std had no object branch at all and called np.nanstd, which fails with
"loop of ufunc does not support argument 0 of type float which has no
callable sqrt method" when the array contains NaN.

Pass keepdims through to count, and compute std on object arrays as
the square root of _nanvar_object.

Co-authored-by: Claude <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant