Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xarray.where() with multiple conditions

I have a dataArray with landcover types. I would like to mask out certain values that I have in a list. Is it possible to use the xr.where() function with multiple conditions?

import numpy as np
import xarray as xr
a = xr.DataArray(np.arange(25).reshape(5, 5), dims=('x', 'y'))
print a
LC = [10,12,19]
a.where((a == LC[0]) | (a == LC[1]))

Which gives:

 <xarray.DataArray (x: 5, y: 5)>
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
Coordinates:
  * x        (x) int64 0 1 2 3 4
  * y        (y) int64 0 1 2 3 4

<xarray.DataArray (x: 5, y: 5)>
array([[ nan,  nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan,  nan],
       [ 10.,  nan,  12.,  nan,  nan],
       [ nan,  nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan,  nan]])
Coordinates:
  * x        (x) int64 0 1 2 3 4
  * y        (y) int64 0 1 2 3 4

The above works for two landcover values, but its tedious to do this for 30 types. Is there a better way?

like image 400
nicway Avatar asked Nov 10 '16 22:11

nicway


People also ask

How do I access Xarray data?

xarray offers extremely flexible indexing routines that combine the best features of NumPy and pandas for data selection. The most basic way to access elements of a DataArray object is to use Python's [] syntax, such as array[i, j] , where i and j are both integers.

What is Python Xarray?

xarray (formerly xray) is an open source project and Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!


1 Answers

xr.DataArray(np.in1d(a, LC).reshape(a.shape),
             dims=a.dims, coords=a.coords)

should do it:

<xarray.DataArray (x: 5, y: 5)>
array([[False, False, False, False, False],
       [False, False, False, False, False],
       [ True, False,  True, False, False],
       [False, False, False, False,  True],
       [False, False, False, False, False]], dtype=bool)
Coordinates:
  * x        (x) int64 0 1 2 3 4
  * y        (y) int64 0 1 2 3 4
like image 118
jhamman Avatar answered Sep 29 '22 05:09

jhamman