Home > Software design >  Assigning a new xarray dataset variable by using strings
Assigning a new xarray dataset variable by using strings

Time:02-04

I would like to create a new variable in my new xarray dataset, and use a string to give my variable name.

Here is an example:

x = xr.Dataset(
        {
            "temperature_c": (
                ("lat", "lon"),
                20 * np.random.rand(4).reshape(2, 2),
            ),
            "precipitation": (("lat", "lon"), np.random.rand(4).reshape(2, 2)),
        },
        coords={"lat": [10, 20], "lon": [150, 160]},
    )

In this example, when calling the assign function, I only can write my new xr dataset variable, "temperature_f" as a non string but a python variable name, and I then obtain a new xr dataset variable with this name:

In [6]: x.assign(temperature_f=x["temperature_c"] * 9 / 5   32)
Out[6]: 
<xarray.Dataset>
Dimensions:        (lat: 2, lon: 2)
Coordinates:
  * lat            (lat) int32 10 20
  * lon            (lon) int32 150 160
Data variables:
    temperature_c  (lat, lon) float64 16.22 15.63 4.918 1.948
    precipitation  (lat, lon) float64 0.7473 0.6274 0.5017 0.1341
    temperature_f  (lat, lon) float64 61.19 60.14 40.85 35.51

I would like to be able to create and assign a new variable by calling a string like this:

x.assign('temperature_f'=x["temperature_c"] * 9 / 5   32)

But I obtain an error.

My goal is being able to create and assign a list of new variables which names are in a list of strings:

variables_names = ['temperature_f', 'temperature_h', 'temperature_i']  
variables_lambdas = [3, 6, 1] 
for i in range(len(variables_names)): x.assign(variables_names[i]=x["temperature_c"] * variables_lambdas[i] / 5   32)

Thanks a lot for helping me ! :)

CodePudding user response:

Xarray datasets can be used like dictionaries:

x = Dataset(...)

variables_names = ['temperature_f', 'temperature_h', 'temperature_i']
variables_lambdas = [3, 6, 1] 
  
for vname, vlambda in zip(variables_names, variables_lambdas):
    x[vname] = x["temperature_c"] * vlambda[i] / 5   32
    
  • Related