python - 我们如何从指定坐标的邻域值中提取最大值?

标签 python python-xarray

如何从指定坐标附近的四个点中提取最大值?

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/

相关文章:

python - 从子文件夹导入模块

python - 在xarray中取一个 "nanmean"

python - 如何使用 groupby 或 resample 对每小时数据进行下采样以根据 python 中一年的天时索引对数据进行分组?

python - 基于像素密度的图像分割

python - 带有groupby的 Pandas 数据框滚动窗口

python - 使用纬度经度坐标从卫星图像获取最近的像素值

python - 如何删除xarray中的网格点?

python - netCDF4.Dataset 到 xarray 数据集的简单转换

python - 使用 Tensorflow 计算数字的百分比

python - 捕获 if 条件中的正则表达式