Skip to content

[Bug] Reduce fails when no axis given #2768

@TomNicholas

Description

@TomNicholas

DataArray.reduce() fails if you try to reduce using a function which doesn't accept any axis arguments.

import numpy as np
from xarray import DataArray

da = DataArray(np.array([[1, 3, 3], [2, 1, 5]]))

def total_sum(data):
    return np.sum(data.flatten())

sum = da.reduce(total_sum)
print(sum)

This should print a dataarray with just the number 15 in it, but instead it throws the error

Traceback (most recent call last):
  File "mwe.py", line 9, in <module>
    sum = da.reduce(total_sum)
  File "/home/tegn500/Documents/Work/Code/xarray/xarray/core/dataarray.py", line 1605, in reduce
    var = self.variable.reduce(func, dim, axis, keep_attrs, **kwargs)
  File "/home/tegn500/Documents/Work/Code/xarray/xarray/core/variable.py", line 1365, in reduce
    axis=axis, **kwargs)
TypeError: total_sum() got an unexpected keyword argument 'axis'

This contradicts what the docstring of .reduce() says:

axis: int or sequence of int, optional
    Axis(es) over which to repeatedly apply func. Only one of the ‘dim’ and ‘axis’ 
    arguments can be supplied. If neither are supplied, then the reduction is 
    calculated over the flattened array (by calling f(x) without an axis argument).

The problem is that in variable.py an axis=None kwarg is always passed to func, even if no axis argument is given by the user in reduce.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions