大量提取网格数据 [英] Numpy extract subset of grid data
问题描述
在我的应用程序中,我有一个值矩阵及其从meshgrid命令获得的坐标(lon,lat). 我想根据经度和纬度限制提取此矩阵的特定子区域.我已经尝试过此解决方案,但是它不起作用.我需要将三个矩阵作为输出,一个用于数据,另两个用于网格.
In my application I have a matrix of values and its coordinates (lon, lat) obtained from a meshgrid command. I want to extract a particular sub-region of this matrix based on longitude and latitude limits. I've tried this solution but it doesn't work. I need as output three matrices one for the data and the other two 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 new values obtained are one dimensional arrays and not matrices. How can I fix this?
推荐答案
从np.where
的观点出发,不能保证您将提取出构成连续矩形子矩阵的值,因此它将其平坦地返回.您可以重塑它们的形状,但是为此您需要弄清楚它们的形状是什么.更好,更通用的解决方案是找到边界框,然后将其提取出来:
There is no guarantee from np.where
's viewpoint that you will extract values that make out a contiguous rectangular submatrix, so it returns them flat. You could reshape 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 that:
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]
这篇关于大量提取网格数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!