如何从 netcdf 文件中提取投影在不规则网格上的变量的像素值?

How to extract pixel value of a variable projected on an irregular grid from a netcdf file?

我有一个包含以下(示例)变量的 netcdf 文件:

纬度

经度

温度

尺寸在 [x, y](像素坐标)中主要是因为纬度和经度都是不规则网格的二维数组。

我想提取温度的像素值,例如。 53.55, 3.5(lat/lon 度小数坐标)。 通常,对于 latitude/longitude 的一维数组,我可以使用 numpy.argmin() 来找到 lat/lon 的索引,从而找到温度变量的像素坐标。

或者,在 xarray 中,我可以使用例如

import xarray as xr
ds = open_dataset(some_file)
ds.close()
ds.temperature.sel(lat=53.55, lon=3.5, method='nearest')

只是我的尺寸现在在 (x, y) 中。可能是由于对 netcdf 数据格式的了解不足,但我很难想出提取所需数据的方法。如何提取我需要的像素值?如果我可以更好地澄清问题,请告诉我。

如果您先计算每个 (2D) 网格点到您请求的位置的距离,您仍然可以使用 argmin()。小例子:

import xarray as xr
import numpy as np

f = xr.open_dataset('tauu.his.NETHERLANDS.NL_W.DOWA_40h12tg2_fERA5_WF2019_fix.201601.nc')

# 2D latitude and longitude
lons = f['lon'].values
lats = f['lat'].values

# Goal latitude and longitude
lon = 4.
lat = 52.

# Calculate distance (in degrees..) for all grid points
distance = np.sqrt( (lons-lon)**2 + (lats-lat)**2 )

# `argmin` on a 2D (or 3D, 4D, ..) field gives the index in the flattened array:
ji  = distance.argmin()

# "Unravel" the index:
j,i = np.unravel_index(ji, lons.shape)

print(lons[j,i], lats[j,i])  # Prints: 3.989169 52.00158

在这种情况下,我只是使用以度为单位的欧氏距离。您总是可以用更花哨或更准确的东西代替它,例如球坐标系中的距离。