Skip to content

Skip nonnumeric variables in Dataset weighted arithmetic - #11833

Merged
headtr1ck merged 12 commits into
pydata:mainfrom
KanishqGandharv219:codex/weighted-nonnumeric
Nov 25, 2026
Merged

headtr1ck merged 12 commits into
pydata:mainfrom
KanishqGandharv219:codex/weighted-nonnumeric

Conversation

@KanishqGandharv219

@KanishqGandharv219 KanishqGandharv219 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

Dataset weighted arithmetic now skips nonnumeric columns instead of failing on them. The change preserves existing sum_of_weights results and lazy Dask count construction, with regression tests for NumPy and Dask.

The filtering is limited to arithmetic reductions. Count operations keep their existing scope, including text/object variables and date columns that start with a missing value. Numeric, temporal and nullable-array compatibility cases are covered alongside the new regressions.

The current filter uses dtype kinds without sampling Dask data. This PR also fixes an unreleased regression introduced by #11868: weighted reductions use the NumPy equivalents of nullable data and weight dtypes to select an accumulator dtype. This preserves integer overflow protection. A separate regression test covers both DataArray and Dataset.

Validation on Windows/Python 3.12.9 (earlier revisions):

  • Full default suite on f0d588d, before the test-only backend adjustment: 16,517 passed, 4,560 skipped, 45 xfailed and 14 xpassed; no failures or collection errors.
  • Updated weighted suite with optional dependencies: 553 passed, 72 existing quantile-method skips.
  • NumPy 2.2/pandas 2.3 without opt_einsum: 524 weighted tests passed, 101 existing skips; all 18 dtype/backend compatibility cases ran.
  • NumPy 2.2/pandas 2.3/SciPy 1.16 without opt_einsum, full default suite: 7,833 passed, 10,047 skipped, 22 xfailed and 7 xpassed; no failures or collection errors.
  • Targeted mypy and applicable pinned changed-file hooks passed.
  • Independent agent review verified the original and updated success/error parity, count preservation and laziness regressions.

Default optional-backend, network and opt-in tests remain skipped. Arithmetic classification of object-Dask data can still compute a sample.

Checklist

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: OpenAI Codex. Task summary: fix #9322, preserve working weighted count behavior, add NumPy/Dask regressions, verify and prepare submission after review. Codex prepared the implementation, tests and this description; a separate agent reviewed the patch.

[Codex on behalf of Kanishq Gandharv]

KanishqGandharv219 and others added 8 commits October 30, 2026 16:29
Filter nonnumeric data variables before weighted arithmetic reductions while
preserving the existing sum_of_weights count scope and lazy Dask behavior.
Add NumPy and Dask regressions and document the change.

Co-authored-by: OpenAI Codex <codex@openai.com>
Compare Dataset weighted results or dtype-promotion errors with DataArray
under both use_opt_einsum settings. This preserves coverage of supported
counts and arithmetic without assuming the optional backend is installed.

Co-authored-by: OpenAI Codex <codex@openai.com>
Compare Dask object counts with unchanged DataArray behavior while keeping
the explicit NumPy expectation. This preserves coverage without assuming
the newer Dask null handling in the minimum-version environment.

Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: OpenAI Codex <codex@openai.com>

@headtr1ck headtr1ck left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @KanishqGandharv219! I think this can be quite a bit simpler. The weighted reductions only work for numbers, booleans and timedeltas (the latter not for var/std). Datetimes and cftime objects fail with a TypeError either way, so keeping them means a dataset with a numeric and a datetime variable still can't be reduced:

ds = xr.Dataset(
    {"num": ("x", [1.0, 2.0, 3.0]), "time": ("x", pd.date_range("2000", periods=3))}
)
ds.weighted(xr.DataArray([1, 2, 3], dims="x")).mean()
# TypeError: unsupported operand type(s) for *: 'int' and 'datetime.datetime'

Filtering on the dtype kind avoids that, and also the special cases for extension arrays and cftime:

if func != self._sum_of_weights:
    dataset = dataset[
        [name for name, var in dataset.data_vars.items() if var.dtype.kind in "biufcm"]
    ]

This keeps nullable Int64 (kind "i") and drops e.g. Categorical (kind "O"). The tests can then shrink to one parametrized test over a few dtypes plus a mixed dataset; the cftime/timezone sum_of_weights and laziness tests are only needed for the cftime check.

KanishqGandharv219 and others added 3 commits November 16, 2026 09:04
Skip datetime and object variables for weighted arithmetic without reading their data. Keep all variables eligible for sum_of_weights.

Co-authored-by: OpenAI Codex <codex@openai.com>
Use the NumPy dtype of pandas nullable data and weights when selecting an accumulator dtype. Retain the incoming integer overflow protection and test both public weighted entry points against scalar expectations.

Co-authored-by: OpenAI Codex <codex@openai.com>
Preserve the reviewed Dataset filtering and nullable accumulator compatibility alongside upstream complex variance handling.

Co-authored-by: OpenAI Codex <codex@openai.com>

@headtr1ck headtr1ck left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update @KanishqGandharv219, the filter looks good now!

Could you still shrink the tests? A single test parametrized over a few dtypes (e.g. float, Int64, timedelta, datetime, string, Categorical) on a mixed dataset, checking which variables are kept for sum_of_weights vs. the other reductions, covers the change. The cftime, timezone and laziness tests aren't needed with the dtype kind check.

The numpy_dtype change in _reduce fixes something different: since #11868 (unreleased), weighted reductions of nullable arrays fail with TypeError: Cannot interpret 'Int64Dtype()' as a data type. That's fine to fix here, since Int64 variables now pass the filter. Please keep test_weighted_nullable_data_and_weights for it and mention it in the PR description.

Co-authored-by: OpenAI Codex <codex@openai.com>

@headtr1ck headtr1ck left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM thanks!

@headtr1ck headtr1ck added the plan to merge Final call for comments label Nov 23, 2026
@headtr1ck
headtr1ck merged commit c9d9817 into pydata:main Nov 25, 2026
64 checks passed
@welcome

welcome Bot commented Nov 25, 2026

Copy link
Copy Markdown

Congratulations on completing your first pull request! Welcome to Xarray! We are proud of you, and hope to see you again! celebration gif

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

Labels

plan to merge Final call for comments

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ds.weighted should skip non-numeric data_vars

2 participants