Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to drop a dimension in xarrray?

I am struggling to drop an entire coordinate/dimensions in xarray. I tried drop_dims, drop_vars, etc. but there are consistently errors.

How do I completely drop the x coordinate/dimension in ds:

data = np.random.randn(2, 3)
labels = ['a', 'b', 'c']
ds = xr.Dataset({'A': (['x', 'y'], data), 'y': labels})

print(ds)

<xarray.Dataset>
Dimensions:  (x: 2, y: 3)
Coordinates:
  * y        (y) <U1 'a' 'b' 'c'
Dimensions without coordinates: x
Data variables:
    A        (x, y) float64 0.2234 -0.6221 -0.2654 -0.9469 1.95 0.07927

As an example, the goal is to drop the x dimension completely (note it also says dimensions without coordinates).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried:

drop = ds.drop_vars('x')

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_3498931/921199433.py in <module>
----> 1 drop = ds.drop_vars('x')

~/miniconda3/envs/py3_std_maps/lib/python3.9/site-packages/xarray/core/dataset.py in drop_vars(self, names, errors)
   4332             names = set(names)
   4333         if errors == "raise":
-> 4334             self._assert_all_in_dataset(names)
   4335 
   4336         variables = {k: v for k, v in self._variables.items() if k not in names}

~/miniconda3/envs/py3_std_maps/lib/python3.9/site-packages/xarray/core/dataset.py in _assert_all_in_dataset(self, names, virtual_okay)
   4302             bad_names -= self.virtual_variables
   4303         if bad_names:
-> 4304             raise ValueError(
   4305                 "One or more of the specified variables "
   4306                 "cannot be found in this dataset"

ValueError: One or more of the specified variables cannot be found in this dataset

How do I completely remove the x variable in the xarray data set?

>Solution :

Try with

ds.sel(x=1, drop=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading