0

this StackOverflow Q/A: Find nearest value in numpy array

shows how to search for a value in a 1D numpy array. What is the xarray equivalent of searching for values close to a target value both within the data searching along the coordinates

import numpy as np
import xarray as xr

def f1(x, y, z):
    return 2*x+3*y+4*z

def f2(x, y, z):
    return x/2+y/3+z/4

TestArray=xr.Dataset({'f1Res':(['xCoord', 'yCoord', 'zcoord'], f1(*np.meshgrid(x, y, z))),
            'f2Res':(['xCoord', 'yCoord', 'zCoord'], f2(*np.meshgrid(x, y, z)))},
                  coords={'xCoord':x, 'yCoord':y, 'zCood':z})

TestArray

So the first search would be to find the locations of the f1Res dataset closest to the target value of -41.2

Second would be to search both the result of f1Res and f2Res simultaneous for the location closest to the target value of 0.1

Third would be to search for the xCoord and yCoord for the results closest to 3.15, -2.5 and leave zCoord open

SKArm
  • 71
  • 1
  • 7

1 Answers1

0

So this is a hack I figured out; but be warned I have not tested it extensively. And it only has been tested on Dataarray

```

def xarraySearch(Target, TargetVal): """ Args: Target: data from xarray TargetVal: target to search for

Return:
    location array 
"""

Res=np.abs(Target-TargetVal).argmin()
ResLoc=np.unravel_index(Res, Target.shape)
return ResLoc

``` I did some tested; preliminary testing on the http://xarray.pydata.org/en/stable/examples/weather-data.html

SKArm
  • 71
  • 1
  • 7