1

np.fabs works fine on xr.DataArray's but not xr.Dataset's.

data = xr.DataArray(np.random.randn(2, 3), coords={'x': ['a', 'b']}, dims=('x', 'y'))
ds = xr.Dataset({'foo': data, 'bar': ('x', [1, 2]), 'baz': np.pi})
np.fabs(ds)
TypeError: ufunc 'fabs' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
np.fabs(ds['foo'])
<xarray.DataArray 'foo' (x: 2, y: 3)>
array([[ 0.384305,  0.161676,  0.07573 ],
       [ 0.789885,  1.299188,  1.965528]])
Coordinates:
  * x        (x) <U1 'a' 'b'
Dimensions without coordinates: y

Any ideas how to apply it to a xr.Dataset?

I could just loop over the variables in the xr.Dataset (see below) but i'm not sure if there is something more efficient

for i, var in enumerate(ds.data_vars):
    ds[var] = np.fabs(ds[var])
Ray Bell
  • 1,508
  • 4
  • 18
  • 45

2 Answers2

7

The easiest way to use do is to use Python's builtin abs() function: abs(ds) should do it.

shoyer
  • 9,165
  • 1
  • 37
  • 55
1

You're looking for the apply method on the Dataset.

In [10]: ds.apply(np.fabs)
Out[10]:
<xarray.Dataset>
Dimensions:  (x: 2, y: 3)
Coordinates:
  * x        (x) <U1 'a' 'b'
Dimensions without coordinates: y
Data variables:
    foo      (x, y) float64 0.2069 2.685 1.815 1.674 1.038 0.5664
    baz      float64 3.142
    bar      (x) float64 1.0 2.0
jhamman
  • 5,867
  • 19
  • 39
  • Thanks a lot. From reading http://xarray.pydata.org/en/stable/generated/xarray.Dataset.apply.html#xarray.Dataset.apply 'Apply a function over the data variables in this dataset.' That totally makes sense. Apologies I didn't pick this up. – Ray Bell Oct 27 '17 at 18:09