Search code examples
pythonpython-xarraykeyword-argument

how to use a string variable to define dataarray name when adding to xarray dataset?


I want to add a dataarray to an xarray dataset, and do so by using xarray.assign, but I don't know how to define the name of the dataarray using a string variable (i.e. to call the new entry "myvar":

import xarray as xr

varname="myvar"
vals=[1,2,3]
coords=[4,5,6]
ds=xr.Dataset(data_vars={},coords={'xcoord':coords})
ds=ds.assign(varname=(['xcoord'],vals))
ds.to_netcdf("test.nc")

ds.close()

This gives me the variable called "varname" - how do I use a variable here?


Solution

  • Construct a dictionary where varname is the key:

    kwargs = {varname: (['xcoord'],vals)}
    

    And then pass that dictionary as the argument to ds.assign(), using ** syntax:

    ds=ds.assign(**kwargs)
    

    If you like, you can do it all in one step, without creating an intermediate dictionary:

    ds=ds.assign(**{varname: (['xcoord'],vals)})