如何从指定坐标附近的四个点中提取最大值?
import xarray as xr
import numpy as np
lat = [0, 10, 20]
lon = [50, 60, 70, 80]
#sample data
test_data = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
#to xarray
data_xarray = xr.DataArray(test_data, dims=("lat","lon"), coords={"lat":lat, "lon":lon})
#<xarray.DataArray (lat: 3, lon: 4)>
#array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
#Coordinates:
# * lat (lat) int64 0 10 20
# * lon (lon) int64 50 60 70 80
data_xarray.plot()
我想实现什么 当lat和lon分别指定5.5和52时,提取周围四个点的最大值10。
最佳答案
使用 sel
的标签索引支持 nearest neighbour lookup .
您可以使用它来查找感兴趣的四个值,重新连接它们,然后计算 max
:
lat_search = 5.5
lon_search = 52
# Select the four nearest values
llat_llon = data_xarray.sel(lat=lat_search, lon=lon_search, method="pad")
ulat_ulon = data_xarray.sel(lat=lat_search, lon=lon_search, method="backfill")
ulat_llon = data_xarray.sel(lat=lat_search, method="backfill").sel(
lon=lon_search, method="pad"
)
llat_ulon = data_xarray.sel(lat=lat_search, method="pad").sel(
lon=lon_search, method="backfill"
)
# Combine the four values providing them in the correct order
ds_grid = [[llat_llon, ulat_llon], [llat_ulon, ulat_ulon]]
neighbours = xr.combine_nested(ds_grid, concat_dim=("lon", "lat"))
# Alternatively, combine them automatically
neighbours = xr.combine_by_coords(
[
x.to_dataset(name="foo").expand_dims(["lat", "lon"])
for x in [llat_llon, ulat_llon, llat_ulon, ulat_ulon]
]
)
# Compute the maximum value
neighbours.max()
我承认手动选择四个值并重新组合它们并不是很优雅(特别是如果您想将其缩放到二维以上)。
我没有看到使用 sel
同时检索两个邻居的通用方法。
如果您有规则间隔的坐标网格,您可以同时选择所有邻居,将切片传递给 sel
:
delta_lat = 10
delta_lon = 10
neighbours = data_xarray.sel(
lat=slice(lat_search - delta_lat, lat_search + delta_lat),
lon=slice(lon_search - delta_lon, lon_search + delta_lon),
)
关于python - 我们如何从指定坐标的邻域值中提取最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65697680/