Dataset.reduce fails wheras Dataarray.reduce succeds
Open
Nobody has claimed this yet.
bug
topic-documentation
- Dominant language
- Python
- Stars
- 4.2k
- Forks
- 1.4k
- Avg merge
- 2d 15h
- Merged PRs (30d)
- 14
Description
What happened?
I tried to reduce dataset using scipy.stats.skew, but it raised an error.
What did you expect to happen?
I expected it to succed, especially because the same operation with dataarray succeeds.
Minimal Complete Verifiable Example
>>> dataset = xr.Dataset(
... {
... "math_scores": (
... ["student", "test"],
... [[90, 85, 92], [78, 80, 85], [95, 92, 98]],
... ),
... "english_scores": (
... ["student", "test"],
... [[88, 90, 92], [75, 82, 79], [93, 96, 91]],
... ),
... },
... coords={
... "student": ["Alice", "Bob", "Charlie"],
... "test": ["Test 1", "Test 2", "Test 3"],
... },
... )
from scipy.stats import skew
# Calling DataArray.reduce on each variable individually succeeds
In [14]: dataset['math_scores'].reduce(skew, dim=["test", 'student'])
Out[14]:
<xarray.DataArray 'math_scores' ()>
array(-0.19423043)
In [15]: dataset['english_scores'].reduce(skew, dim=["test", 'student'])
Out[15]:
<xarray.DataArray 'english_scores' ()>
array(-0.60125)
# But calling Dataset.reduce fails
dataset.reduce(skew, dim=["test", 'student'])
--------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[16], line 1
----> 1 dataset.reduce(skew, dim=["test", 'student'])
File ~/Documents/Work/Code/xarray/xarray/core/dataset.py:5972, in Dataset.reduce(self, func, dim, keep_attrs, keepdims, numeric_only, **kwargs)
5955 if (
5956 # Some reduction functions (e.g. std, var) need to run on variables
5957 # that don't have the reduce dims: PR5393
(...)
5965 # the former is often more efficient
5966 # keep single-element dims as list, to support Hashables
5967 reduce_maybe_single = (
5968 None
5969 if len(reduce_dims) == var.ndim and var.ndim != 1
5970 else reduce_dims
5971 )
-> 5972 variables[name] = var.reduce(
5973 func,
5974 dim=reduce_maybe_single,
5975 keep_attrs=keep_attrs,
5976 keepdims=keepdims,
5977 **kwargs,
5978 )
5980 coord_names = {k for k in self.coords if k in variables}
5981 indexes = {k: v for k, v in self._indexes.items() if k in variables}
File ~/Documents/Work/Code/xarray/xarray/core/variable.py:2045, in Variable.reduce(self, func, dim, axis, keep_attrs, keepdims, **kwargs)
2042 keep_attrs = _get_keep_attrs(default=False)
2043 attrs = self._attrs if keep_attrs else None
-> 2045 return Variable(dims, data, attrs=attrs)
File ~/Documents/Work/Code/xarray/xarray/core/variable.py:367, in Variable.__init__(self, dims, data, attrs, encoding, fastpath)
347 """
348 Parameters
349 ----------
(...)
364 unrecognized encoding items.
365 """
366 self._data = as_compatible_data(data, fastpath=fastpath)
--> 367 self._dims = self._parse_dimensions(dims)
368 self._attrs = None
369 self._encoding = None
File ~/Documents/Work/Code/xarray/xarray/core/variable.py:683, in Variable._parse_dimensions(self, dims)
681 dims = tuple(dims)
682 if len(dims) != self.ndim:
--> 683 raise ValueError(
684 f"dimensions {dims} must have the same length as the "
685 f"number of data dimensions, ndim={self.ndim}"
686 )
687 return dims
ValueError: dimensions () must have the same length as the number of data dimensions, ndim=1
MVCE confirmation
- Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- Complete example — the example is self-contained, including all data and the text of any traceback.
- Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
- New issue — a search of GitHub Issues suggests this is not a duplicate.
Relevant log output
No response
Anything else we need to know?
No response
Environment
xarray main branch
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducer using scipy.stats.skew, then inspect Dataset.reduce in xarray/core/dataset.py and Variable.reduce in xarray/core/variable.py. Compare the successful DataArray reduction with the failing Dataset reduction and verify that the dataset result preserves compatible dimensions for both variables.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- data
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100