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

1

8

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.

Midwife answered 15/1, 2019 at 11:32 Comment(0)
G
13

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)
Grossman answered 15/1, 2019 at 12:21 Comment(2)
You can also use xr.where with the same call and get back a instead of a.valuesCrowther
Yes, you should be using the xr.where function: xarray.pydata.org/en/stable/generated/…Glutinous

© 2022 - 2024 — McMap. All rights reserved.