Search code examples
pythonpython-xarray

How to reshape a xarray Dataset?


I have a xarray.Dataset named seisnc_2d with dimensions 'x': 240200, 'y': 2001 these are 200 seismic shots, each seismic shot has a dimension (1201,2001), which means that the n shot will be seisnc_2d.isel(x=slice((n-1)*1201, n*1201)).

What I want is to somehow reshape this dataset with a new dimension shot, leaving the new seisnc_2d dimensions as 'shot':200, 'x': 1201, 'y': 2001 so instead of doing the x slice every time I need a seismic shot data, just refer to it as, I guess something like seisnc_2d.isel(shot=n)


Solution

  • As described in the user guide one can use a combination of coarsen and construct to reshape the dataset in the desired way:

    import numpy as np
    import xarray as xr
    
    ds = xr.Dataset({"foo": (("x", "y"), np.zeros((240200, 2001)))})
    coarse_construct = ds.coarsen(x=1201).construct(x=("shot", "x"))
    print(coarse_construct.isel(shot=0))  # => Dimensions:  (x: 1201, y: 2001)