Set data array elements depending on a condition.
Elements are set differently depending on where the condition is True or False. Two assignment values are given. From one of them, the field’s data array is set where the condition is True and where the condition is False, the data array is set from the other.
Each assignment value may either contain a single datum, or is an array-like object which is broadcastable shape of the field’s data array.
Missing data
The treatment of missing data elements depends on the value of field’s hardmask attribute. If it is True then masked elements will not unmasked, otherwise masked elements may be set to any value.
In either case, unmasked elements may be set to any value (including missing data).
Unmasked elements may be set to missing data by assignment to the cf.masked constant or by assignment to a value which contains masked elements.
Parameters: |
|
---|---|
Returns: |
|
Examples: |
Set data array values to 15 everywhere:
>>> f.where(True, 15)
This example could also be done with subspace assignment:
>>> f.subspace[...] = 15
Set all negative data array values to zero and leave all other elements unchanged:
>>> g = f.where(f<0, 0)
Multiply all positive data array elements by -1 and set other data array elements to 3.14:
>>> g = f.where(f>0, -f, 3.14)
Set all values less than 280 and greater than 290 to missing data:
>>> g = f.where((f < 280) | (f > 290), cf.masked)
This example could also be done with a cf.Query object:
>>> g = f.where(cf.wo(280, 290), cf.masked)
or equivalently:
>>> g = f.where(f==cf.wo(280, 290), cf.masked)
Set data array elements in the northern hemisphere to missing data:
>>> # Create a condition which is True only in the northern hemisphere
>>> condition = f.mask
>>> condition.subspace[...] = False
>>> condition.subspace[f.indices(latitude=cf.ge(0))] = True
>>> # Set the data
>>> g = f.where(condition, cf.masked)
This example could also be done with subspace assignment:
>>> g = f.subspace[f.indices(latitude=cf.ge(0))] = cf.masked
Set a field’s polar rows to their average values and all other points to missing data:
>>> # Calculate zonal means at all latitudes
>>> m = f.collapse('longitude: mean')
>>> # Create a condition which is True only on the polar rows
>>> condition = f.mask
>>> condition.subspace[...] = False
>>> condition.subspace[f.indices(latitude=cf.set([-90, 90]))] = True
>>> # Set the data
>>> g = f.where(condition, m, cf.masked)