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

标签 python numpy netcdf python-xarray

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

纬度

经度

温度

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

我想提取例如中的温度像素值。 53.55, 3.5(纬度/经度十进制坐标)。 通常,对于一维纬度/经度数组,我可以使用 numpy.argmin() 来查找纬度/经度的索引,从而找到温度变量的像素坐标。

或者,在 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

在本例中,我简单地使用了以度为单位的欧几里得距离。您始终可以用更奇特或更准确的东西来替换它,例如球坐标中的距离。

关于python - 如何从 netcdf 文件中提取投影在不规则网格上的变量的像素值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992490/

相关文章:

python - 省略自定义 Django 用户模型的密码字段

python - 如何合并 2 个 JSON 文件?

python - 读入格式化行以填充数组

python - 名称 'sp' 未明确定义

linux - 平均多个 .nc 文件 - Linux 上的 NCO 运算符

python - Python中通过散点提取二维网格场的值

python - 在 Mac 上解析 XML 时出现 UnicodeDecodeError,但在 PC 上可以正常工作

python - 密码保护整个 Django 应用程序

python - 使用 MatPlotLib 和 Numpy 将高斯拟合到直方图 - Y 缩放错误?

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