A brief way to filter data in xarray

I need to apply a very simple matching operator to values ​​in an xarray array:

  • If value> 0, do 2
  • If value == 0, do 0
  • If value NaN, doNaN

Here is my current solution. I use NaNs, .fillnaand the type of constraint instead of indexing 2d.

valid = date_by_items.notnull()
positive = date_by_items > 0
positive = positive * 2
result = positive.fillna(0.).where(valid)
result

This changes this:

In [20]: date_by_items = xr.DataArray(np.asarray((list(range(3)) * 10)).reshape(6,5), dims=('date','item'))
    ...: date_by_items
    ...: 
Out[20]: 
<xarray.DataArray (date: 6, item: 5)>
array([[0, 1, 2, 0, 1],
       [2, 0, 1, 2, 0],
       [1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1],
       [2, 0, 1, 2, 0],
       [1, 2, 0, 1, 2]])
Coordinates:
  * date     (date) int64 0 1 2 3 4 5
  * item     (item) int64 0 1 2 3 4

... to that:

Out[22]: 
<xarray.DataArray (date: 6, item: 5)>
array([[ 0.,  2.,  2.,  0.,  2.],
       [ 2.,  0.,  2.,  2.,  0.],
       [ 2.,  2.,  0.,  2.,  2.],
       [ 0.,  2.,  2.,  0.,  2.],
       [ 2.,  0.,  2.,  2.,  0.],
       [ 2.,  2.,  0.,  2.,  2.]])
Coordinates:
  * date     (date) int64 0 1 2 3 4 5
  * item     (item) int64 0 1 2 3 4

For now, pandas df[df>0] = 2will be enough. Surely, I'm doing something pedestrian, and there is a way:

+4
source share
2 answers

xarray now supports .where(condition, other), so now it really is:

result = date_by_items.where(date_by_items > 0, 2)
+1
source

NumPy, DataArray NumPy:

date_by_items.values[date_by_items.values > 0] = 2

, xarray other where, (, - !). , date_by_items.where(date_by_items > 0, 2).

, .

+3

Source: https://habr.com/ru/post/1650848/


All Articles