diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 01cdca7aecf..fb9d9dfa910 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -94,6 +94,10 @@ Bug fixes - Masking data arrays with :py:meth:`xarray.DataArray.where` now returns an array with the name of the original masked array (:issue:`2748` and :issue:`2457`). By `Yohai Bar-Sinai `_. +- Fixed error when trying to reduce a DataArray using a function which does not + require an axis argument. (:issue:`2768`) + By `Tom Nicholas `_. + - Per `CF conventions `_, specifying ``'standard'`` as the calendar type in diff --git a/xarray/core/variable.py b/xarray/core/variable.py index 85eab294619..b675317d83d 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -1361,8 +1361,11 @@ def reduce(self, func, dim=None, axis=None, if dim is not None: axis = self.get_axis_num(dim) - data = func(self.data if allow_lazy else self.values, - axis=axis, **kwargs) + input_data = self.data if allow_lazy else self.values + if axis is not None: + data = func(input_data, axis=axis, **kwargs) + else: + data = func(input_data, **kwargs) if getattr(data, 'shape', ()) == self.shape: dims = self.dims diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index e4ffdad4260..c26968b1db0 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -3633,11 +3633,28 @@ def mean_only_one_axis(x, axis): actual = ds.reduce(mean_only_one_axis, 'y') assert_identical(expected, actual) - with raises_regex(TypeError, 'non-integer axis'): + with raises_regex(TypeError, "missing 1 required positional argument: " + "'axis'"): ds.reduce(mean_only_one_axis) with raises_regex(TypeError, 'non-integer axis'): - ds.reduce(mean_only_one_axis, ['x', 'y']) + ds.reduce(mean_only_one_axis, axis=['x', 'y']) + + def test_reduce_no_axis(self): + + def total_sum(x): + return np.sum(x.flatten()) + + ds = Dataset({'a': (['x', 'y'], [[0, 1, 2, 3, 4]])}) + expected = Dataset({'a': ((), 10)}) + actual = ds.reduce(total_sum) + assert_identical(expected, actual) + + with raises_regex(TypeError, "unexpected keyword argument 'axis'"): + ds.reduce(total_sum, axis=0) + + with raises_regex(TypeError, "unexpected keyword argument 'axis'"): + ds.reduce(total_sum, dim='x') def test_quantile(self):