在 python 中按纬度和经度从 .nc 文件中提取数据

Extracting data from .nc file by latitude and longitude in python

我有 .nc 格式的网格化数据集。我想根据纬度和经度提取数据。我的数据集的纬度和经度如下所示:

import netCDF4
from netCDF4 import Dataset
f= Dataset('data.nc')
f.variables['lat'][:]
array([ 31.5,  30.5,  29.5,  28.5,  27.5,  26.5,  25.5,  24.5,  23.5,
        22.5,  21.5,  20.5,  19.5,  18.5], dtype=float32)

f.variables['lon'][:]
array([ 60.5,  61.5,  62.5,  63.5,  64.5,  65.5,  66.5,  67.5,  68.5,
        69.5,  70.5,  71.5,  72.5,  73.5,  74.5,  75.5,  76.5,  77.5,
        78.5,  79.5,  80.5,  81.5,  82.5,  83.5,  84.5,  85.5,  86.5,
        87.5,  88.5,  89.5,  90.5,  91.5], dtype=float32)

假设我想提取 lat = 29.5 和 lon = 65.5 的数据 那么哪个代码是正确的?

f.variables['temp'][:,2,5]

f.variables['temp'][:,29.5,65.5]

非常感谢您的建议!

这段代码肯定行不通:

f.variables['temp'][:,29.5,65.5]

因为你不能(不应该)用 numpynetcdf4 中的浮点数索引。

如果你想按值索引,我建议你查看 xarray:

import xarray as xr
ds = xr.open_dataset('data.nc')
# index by value
ds['temp'].sel(lon=65.5, lat=29.5)
# or index by position
ds['temp'].isel(lon=5, lat=2)

如果 'temp' 变量是按纬度、经度标注的,则以下是正确的。一些 NetCDF 变量的维度是 lon,lat

f.variables['temp'][:,2,5]

您可以检查 'temp' 变量的维度。

print f.variables['temp'].dimensions

搜索最接近值的经纬度索引的代码: