【问题标题】:Extracting data from .nc file by latitude and longitude in python在python中按纬度和经度从.nc文件中提取数据
【发布时间】:2016-10-21 18:16:03
【问题描述】:

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

您的建议将不胜感激!

【问题讨论】:

标签: python numpy gdal netcdf


【解决方案1】:

这段代码肯定行不通:

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)

【讨论】:

    【解决方案2】:

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

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

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

    print f.variables['temp'].dimensions
    

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 2012-06-18
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多