Skip to content

xarray groupby does not drop dimension when squeeze #6173

Answered by mathause
ecimoli asked this question in Q&A
Discussion options

You must be logged in to vote

Here is a small example. Kind of works

import numpy as np
import xarray as xr

data = np.arange(8).reshape(2, 4)
da = xr.DataArray(data, dims=("y", "x"), coords=dict(y=[1, 2], x=[1, 1, 1, 1]))

da = da.stack(gridcell=("x", "y"))

da_g = da.groupby("gridcell").mean()

It keeps the multiindex but renames the levels (this could be considered a bug).

<xarray.DataArray (gridcell: 2)>
array([1.5, 5.5])
Coordinates:
  * gridcell          (gridcell) MultiIndex
  - gridcell_level_0  (gridcell) int64 1 1
  - gridcell_level_1  (gridcell) int64 1 2

This can be fixed like so:

mi = da_g.indexes["gridcell"]
da_g.assign_coords(gridcell=mi.set_names(["x", "y"]))

Do you experience something different? If s…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@ecimoli
Comment options

Comment options

You must be logged in to vote
1 reply
@ecimoli
Comment options

Answer selected by andersy005
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants