xarray.Dataset.eval#

Dataset.eval(statement, *, parser=Default.token)[source]#

Calculate an expression supplied as a string in the context of the dataset.

This is currently experimental; the API may change particularly around assignments, which currently return a Dataset with the additional variable.

Logical operators (and, or, not) are automatically transformed to bitwise operators (&, |, ~) which work element-wise on arrays.

Parameters:

statement (str) – String containing the Python-like expression to evaluate.

Returns:

result (Dataset or DataArray, depending on whether ``statement` contains an`) – assignment.

Warning

Like pd.eval(), this method should not be used with untrusted input.

Examples

>>> ds = xr.Dataset(
...     {"a": ("x", np.arange(0, 5, 1)), "b": ("x", np.linspace(0, 1, 5))}
... )
>>> ds
<xarray.Dataset> Size: 80B
Dimensions:  (x: 5)
Dimensions without coordinates: x
Data variables:
    a        (x) int64 40B 0 1 2 3 4
    b        (x) float64 40B 0.0 0.25 0.5 0.75 1.0
>>> ds.eval("a + b")
<xarray.DataArray (x: 5)> Size: 40B
array([0.  , 1.25, 2.5 , 3.75, 5.  ])
Dimensions without coordinates: x
>>> ds.eval("c = a + b")
<xarray.Dataset> Size: 120B
Dimensions:  (x: 5)
Dimensions without coordinates: x
Data variables:
    a        (x) int64 40B 0 1 2 3 4
    b        (x) float64 40B 0.0 0.25 0.5 0.75 1.0
    c        (x) float64 40B 0.0 1.25 2.5 3.75 5.0