Consider the following example below using DataArray:
In [34]: import xarray as xr
In [35]: da=xr.DataArray(np.random.rand(5,5,5), dims=['x', 'y', 'z'], coords=dict(x=range(5), y=range(5), z=range(5)))
In [36]: da.mean()
Out[36]: 
<xarray.DataArray ()>
array(0.547996)
The type of the returned object from the mean operation is actually a DataArray without any dimensions. However, sometimes this is cumbersome and I'd like xarray to return a good ol' float at those times. Is this possible? Ideally there would be something like `xr.options.return_mode' or something like that (instead of having to use an extra argument in every function).
At present, xarray doesn't have anything like xr.options.return_mode. From the xarray documentation:
xarray tries hard to be self-consistent: operations on a DataArray (resp. Dataset) return another DataArray (resp. Dataset) object. In particular, operations returning scalar values (e.g. indexing or aggregations like mean or sum applied to all axes) will also return xarray objects.
Unfortunately, this means we sometimes have to explicitly cast our results from xarray when using them in other libraries.
So either of these should work if you want a python scalar:
float(da.mean())
or
da.mean().item()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With