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

时间:2016-06-20 13:06:30

标签: python numpy gdal netcdf

我有.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]

你的建议将受到高度赞赏!

2 个答案:

答案 0 :(得分:3)

此代码肯定不起作用:

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)

答案 1 :(得分:2)

如果'temp'变量的尺寸为lat,lon,则下面是正确的。一些NetCDF变量的大小为lon,lat

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

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

print f.variables['temp'].dimensions

搜索最接近值的lat,lon索引的代码:

https://stackoverflow.com/a/33793437/1211981