Mask DataArray values outside given range
See original GitHub issueI did a quick search and couldn’t find anything like this.
I often find that I need to remove values outside of a certain range (i.e. mask values outside a range to NaN). This means I usually use xr.DataArray.where
. However, this is not easy to do when you’re piping operations and the initial array is not equivalent to the modified DataArray you’re operating on.
# this is difficult to do when chaining/piping operations
xda = xda.where((xda > minval) & (xda < maxval))
xr.DataArray.clip
achieves something similar, but does not mask the output. It would be great if xr.DataArray.clip
or an equivalent could return an array where outside the min and max is the specified value (e.g. NaN). Alternatively, new functions could be added to DataArray as between
/outside
.
The first option would be to overload the implementation of np.clip
, but either way, functionally it would be doing something like in the hacky solution below:
def between(self, min=-np.inf, max=np.inf, return_value=np.NaN):
xda = self.copy()
mask = ((xda < min) | (xda > max)).values
xda.values[mask] = return_value
return xda
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (2 by maintainers)
Sorry @luke-gregor I totally misunderstood your code!
we need to update the docstrings, right now the only way to learn about that is by reading the examples.
I’m reopening this to make sure we won’t forget.