-
I just came across this unexpected behaviour (at least for me ;-) ) regarding unstacking a DataArray. What I want to do, in a nutshell, is to
The last operation somehow fails (it does nothing). I would like to understand why and especially how to achieve this last step? The problem seems to be related to #5989, but as far as I can see, I do what is suggested there as a solution. Minimal working exampleimport xarray as xr
da = xr.DataArray(
[[1, 2.], [3, 4]],
dims=['lat', 'lon'],
coords=dict(lon=[5., 10], lat=[10., 12])
)
# 1. stack a `DataArray`
da_stacked = da.stack(x=('lat', 'lon'))
stacked_coords = da_stacked.coords['x']
# 2. replace the new `MultiIndex` with a 1D index
new_coords = np.arange(stacked_coords.size)
da_stacked = da_stacked.assign_coords(x=new_coords)
# 3. <...do some operations...>
# nothing happens
# 4. reassign the original `MultiIndex`
da_stacked = da_stacked.assign_coords(x=stacked_coords)
# 5. unstack the `DataArray` to obtain the original shape.
da_stacked.unstack() Result of the last line of code>>> xarray.DataArray (x: 4)
array([1., 2., 3., 4.])
Coordinates:
x (x) object MultiIndex
lat (x) float64 10.0 10.0 12.0 12.0
lon (x) float64 5.0 10.0 5.0 10.0
Attributes: (0) What I actually expected: the input
|
Beta Was this translation helpful? Give feedback.
Answered by
mathause
Dec 1, 2022
Replies: 1 comment 4 replies
-
In step 4 you can do |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
nicrie
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In step 4 you can do
data = data.set_index(x=('lat', 'lon'))
and thendata.unstack("x")