How to drop all coordinates and variables without dimensions in xarray

22 Views Asked by At

How can I drop all xarray Dataset coordinates and variables that don't have any dimensions? In this example, I want to drop item and nothing from this Dataset.

import xarray as xr

ds = xr.Dataset(
    {"temperature": (["x", "y"], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]), "nothing": 10},
    coords={"item": "hi", "x": [1, 2, 3], "y": [1, 2, 3]},
)
ds

enter image description here

I could of course use ds.drop_vars(["item", "nothing"]), but I was expecting a different method like ds.drop_dims() or ds.squeeze() could do this without me specifying which to drop.

An alternative way to look at this question is, how can I select only coordaintes and variables where the dimension is (x,y)?

1

There are 1 best solutions below

0
jhamman On BEST ANSWER

Xarray doesn't have exactly what you are looking for but something like this should work:

ds.drop_vars(lambda x: [v for v, da in x.variables.items() if not da.ndim])