A subset of the extracted data in the grid

In my application, I have a matrix of values ​​and its coordinates (lon, lat) obtained from the meshgrid command. I want to extract a specific sub-region of this matrix based on longitude and latitude constraints. I tried this solution but it doesn't work. I need as output three matrices for the data and two others for the grid.

Lons, Lats = meshgrid(X, Y)
indexes = np.where((Lons < MLon) & (Lons > mLon) & (Lats < MLat) & (Lats > mLat))
newLons = Lons[indexes]
newLats = Lats[indexes]
newData = Data[indexes]

      

The newly retrieved values ​​are one-dimensional arrays, not matrices. How can I fix this?

+3


source to share


1 answer


There is no guarantee from the point of view np.where

that you will be retrieving values ​​that make up a solid rectangular submatrix, so it returns them flush. You can redo them, but for that you need to figure out what their shape is. A better and more general solution would be to find the bounding box and then extract it:



Xspan = np.where((X < MLon) & (X > mLon))[0][[0, -1]]
Yspan = np.where((Y < MLat) & (Y > mLat))[0][[0, -1]]

# Create a selection
sel = [slice(Xspan[0], Xspan[1] + 1), slice(Yspan[0], Yspan[1] + 1)]

# Extract
newLons = Lons[sel]  # == Lons[Xspan[0]:Xspan[1]+1, Yspan[0]:Yspan[1]+1]
newLats = Lats[sel]
newData = Data[sel]

      

+2


source







All Articles