JackLidge
JackLidge

Reputation: 441

Mask data in an xarray and changing values for both True and False responses

I have an xarray DataArray which contains data from multiple days. I am able to mask it using the .where function for one condition, but I'd like to make all values over a certain value 1 and all values under that value 0. Ideally, I;d also like to ensure that any np.nans in the dataset are not changed, but this is not a requirement.

import numpy as np
import xarray as xr

dval = np.random.randint(5,size=[3,4,4])
x = [0,1,2,3]
y = [0,1,2,3]
time = ['2017-10-13','2017-10-12','2017-10-11']

a = xr.DataArray(dval,coords=[time,x,y],dims=['time','x','y'])
a = a.where(a>2,1,0) #ideally this would work as (condition,True val, False val)

This results in a ValueError of "cannot set 'other' if drop=True"

Any help with this would be greatly appreciated.

Upvotes: 8

Views: 12390

Answers (1)

Gozy4
Gozy4

Reputation: 484

a = a.where(a>2, 1, 0) won't work because the DataArray.where method only supports setting other. Basically you are doing: a = a.where(a>2, other=1, drop=0).

Instead, you should using the xarray's 3 argument xr.where function:

a= xr.where(a>2, 1, 0)

Upvotes: 14

Related Questions