Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

keepdims=True for xarray reductions #2170

Closed
shoyer opened this issue May 22, 2018 · 3 comments · Fixed by #3033
Closed

keepdims=True for xarray reductions #2170

shoyer opened this issue May 22, 2018 · 3 comments · Fixed by #3033

Comments

@shoyer
Copy link
Member

shoyer commented May 22, 2018

For operations where arrays are aggregated but then combined, the keepdims=True option for NumPy aggregations is convenient.

We should consider supporting this in xarray as well. Aggregating a DataArray/Dataset with keepdims=True (or maybe keep_dims=True) would remove all original coordinates along aggregated dimensions and return a result with a dimension of size 1 without any coordinates, e.g.,

>>> array = xr.DataArray([1, 2, 3], dims='x', coords={'x': ['a', 'b', 'c']})
>>> array.mean(keepdims=True)
<xarray.DataArray (x: 1)>
array([2.])
Dimensions without coordinates: x

In case, array.mean(keepdims=True() is equivalent to array.mean().expand_dims('x') but in general this equivalent does not hold, because the location of the original dimension is lost.

Implementation-wise, we have two options:

  1. Pass on keepdims=True to NumPy functions like numpy.mean(), or
  2. Implement keepdims=True ourselves, in Variable.reduce().

I think I like option 2 a little better, because it places fewer requirements on aggregation functions. For example, functions like bottleneck.nanmean() don't accept a keepdims argument.

@seth-p
Copy link
Contributor

seth-p commented Jul 23, 2018

I second this request.

The following may not be optimal, but seems to work for me as a keepdims=True version of reduce():

    def dim_preserving_reduce(self, func, dim=None, axis=None, label=None, keep_attrs=False, **kwargs):
        if axis is not None:
            dim = np.take(self._obj.dims, axis, mode='wrap')
        dims = dim if isinstance(dim, (list, tuple)) else [dim]
        dims_coords = {dim: [lab] for dim, lab in zip(dims, (label if isinstance(label, list) else [label]))}
        return self._obj.reduce(func, dim=dims, keep_attrs=keep_attrs, **kwargs). \
            expand_dims(dims, axis=[self._obj.dims.index(dim) for dim in dims]). \
            assign_coords(**dims_coords)

@aldanor
Copy link

aldanor commented Mar 20, 2019

Please!

It's really painful in some cases where keepdims option is not available, tons of unneeded boilerplate required to mimic the same thing.

@shoyer
Copy link
Member Author

shoyer commented Mar 20, 2019

Pull requests would be very welcome here.

@dcherian dcherian pinned this issue Apr 11, 2019
ScottWales pushed a commit to ScottWales/xarray that referenced this issue Jun 19, 2019
Addresses pydata#2170

Add new option `keepdims` to xarray reduce operations, following the
behaviour of Numpy.

`keepdims` may be passed to reductions on either Datasets or DataArrays,
and will result in the reduced dimensions being still present in the
output with size 1.

Coordinates that depend on the reduced dimensions will be removed from
the Dataset/DataArray
shoyer pushed a commit that referenced this issue Jun 23, 2019
* ENH: keepdims=True for xarray reductions

Addresses #2170

Add new option `keepdims` to xarray reduce operations, following the
behaviour of Numpy.

`keepdims` may be passed to reductions on either Datasets or DataArrays,
and will result in the reduced dimensions being still present in the
output with size 1.

Coordinates that depend on the reduced dimensions will be removed from
the Dataset/DataArray

* Set the default to be `False`

* Correct lint error

* Apply suggestions from code review

Co-Authored-By: Maximilian Roos <[email protected]>

* Add test for dask and fix implementation

* Move 'keepdims' up to where 'dims' is set

* Fix lint, add test for scalar variable
@shoyer shoyer unpinned this issue Jun 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants