Skip to content

unstack() appears to fail to unstack a MultiIndex under specific circumstances. What's going on? #5989

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

You must be logged in to vote

Assigning d1 or d1 your ds_stacked looses the MultiIndex compare

Before:

<xarray.Dataset>
Dimensions:        (z: 4)
Coordinates:
  * z              (z) MultiIndex
  - x              (z) int64 0 0 1 1
  - y              (z) int64 0 1 0 1

After:

<xarray.Dataset>
Dimensions:        (z: 4)
Coordinates:
  * z              (z) object (0, 0) (0, 1) (1, 0) (1, 1)
    lon            (z) float64 -99.83 -99.32 -99.79 -99.23
    lat            (z) float64 42.25 42.21 42.63 42.59

I am not entirely why this happens... But to work around this issue you have two possibilities:

# assign a raw array
ds_stacked['label'] = ("z", d1.data)

# add the correct coords
d2 = d2.assign_coords(z=ds_stacked.z)
ds_stacked

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by keewis
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