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

Best way to perform DataArray.mean while retaining coords defined in the dimension being averaged #1497

Closed
spencerahill opened this issue Jul 30, 2017 · 2 comments

Comments

@spencerahill
Copy link
Contributor

DataArray.mean applied along a particular dimension causes coordinates that are defined in that dimension to be dropped:

In [39]: x, y = range(2), range(3)
In [40]: arr = xr.DataArray(np.random.random((2,3)), dims=['x', 'y'], coords=dict(x=x, y=y))
In [41]: coord = xr.DataArray(np.random.random((2,3)), dims=['x', 'y'], coords=dict(x=x, y=y))
In [42]: arr = arr.assign_coords(z=coord)
In [43]: arr
Out[43]:
<xarray.DataArray (x: 2, y: 3)>
array([[ 0.132368,  0.746242,  0.48783 ],
       [ 0.12747 ,  0.751283,  0.033713]])
Coordinates:
  * y        (y) int64 0 1 2
  * x        (x) int64 0 1
    z        (x, y) float64 0.993 0.1031 0.1808 0.2769 0.7237 0.2891

In [44]: arr.mean('x')
Out[44]:
<xarray.DataArray (y: 3)>
array([ 0.129919,  0.748763,  0.260772])
Coordinates:
  * y        (y) int64 0 1 2

We have a use case where we'd like to preserve the coordinates. @spencerkclark came up with the following workaround, which entails converting to a dataset, promoting the coord to a variable, performing the mean, and demoting the original coord back from a variable to a coord:

def coord_preserving_mean(arr, *args, **kwargs):
    name = arr.name
    ds = arr.reset_coords()
    names = set(arr.coords) - set(arr.dims)
    ds = ds.mean(*args, **kwargs)
    return ds.set_coords(names)[name]

This works fine, but I just feel like maybe there's an easier way to do this that we're missing. Any ideas? Thanks in advance.

xref spencerahill/aospy#194

@shoyer
Copy link
Member

shoyer commented Jul 31, 2017

What exactly does the desired array look like in your example?

@spencerahill
Copy link
Contributor Author

No longer needed; closing

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

No branches or pull requests

2 participants