简体   繁体   中英

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

I have gridded datasets in .nc format. I want to extract data on the basis of latitude and longitude. Latitude and longitude of my datasets are shown below:

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)

suppose I want to extract the data for lat = 29.5 and lon = 65.5 then which code is correct?

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

or

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

yours suggestion will be highly appreciated!

This code will certainly not work:

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

since you can't (shouldn't) index with floats in numpy or netcdf4 .

If you want to index by value, I'd suggest checking out 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)

Below is correct if the 'temp' variable is dimensioned by lat,lon. Some NetCDF variables are dimensioned by lon,lat

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

You can check the dimensions of the 'temp' variable.

print f.variables['temp'].dimensions

Code to search for lat,lon indexes nearest a value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM