14

I am looking for a way of extracting a list of the data variable names (strings) from a xarray.DataSet object. I have used xr_object.data_vars and xr_object.data_vars.keys() but they don't seem to give anything usefull.

Also, the docs of xarray don't seem show that xarray has a built in method or attribute for getting something similar.

Anybody knows how to do so?

Thomas
  • 153
  • 1
  • 1
  • 6

2 Answers2

16

Your question is a little ambigous. I guess you know that

xr_object.keys()

would give you a view of the dataset keys.

if you just need to put it to a list, then a list() function would do it ( at least after V0.11 ): (ds is the xr_object)

list(ds.keys())

and if you need dimensions too:

list(ds.coords)
fenixnano
  • 262
  • 2
  • 9
  • 1
    @Thomas that's not silly at all! the result of the `.keys()` doesn't look like a list, I guess there is an internal api of xarray that is called to allow this to happen. Also, please consider accept this as awnser if it solves your problem. – fenixnano Oct 12 '20 at 00:04
  • 3
    `list(xrds.data_vars)` also works – climatestudent Feb 26 '22 at 21:56
  • 3
    `list(ds)` seems to return the list of variables as well, it also works with data frames by the way `list(df)` returns the list of columns of a pandas data frame but I'm not sure if it's a recommended usage. I'll stick to `list(ds.data_vars)` for now. Thank you. – Paul Rougieux Feb 10 '23 at 12:07
8

I think there is the result you want.

#a list with the variable names of your xarray.Dataset
res = [i.name for i in xr_object.data_vars] 
SCKU
  • 783
  • 9
  • 14