如何在 xarray 中删除一个维度?

How to drop a dimension in xarrray?

我正在努力将整个 coordinate/dimensions 放入 xarray。我尝试了 drop_dims、drop_vars 等,但始终存在错误。

如何在 ds 中完全删除 x coordinate/dimension:

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

例如,目标是完全删除 x 维度(注意它也表示没有坐标的维度)。

我试过了:

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

如何彻底删除xarray数据集中的x变量?

试试

ds.sel(x=1, drop=True)