用Python按纬度和经度从.nc文件中提取数据

3

我有一些以 .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)

假设我想提取纬度为29.5和经度为65.5的数据,那么哪段代码是正确的?
f.variables['temp'][:,2,5]

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

非常感谢您的建议!


3
你尝试过你所提议的选项吗?请查看http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html。 - Benjamin
2个回答

4

这段代码肯定不能工作:

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

自从在 numpy 或者 netcdf4 中不能(不应该)使用浮点数来进行索引之后,如果你想通过值进行索引,我建议你查看一下 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)

2
如果“temp”变量的维度是lat,lon,则以下内容是正确的。一些NetCDF变量的维度是lon,lat。
f.variables['temp'][:,2,5]

您可以检查“temp”变量的尺寸。

print f.variables['temp'].dimensions

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

https://dev59.com/x5Hea4cB1Zd3GeqPmTk1#33793437


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接