3/8/2018 - 6:38 AM

Read a datapoint from netcdf file.

Extract any datapoint (latitude, longitude) from netcdf file. Really this script read a list of files. They are appended. Furthermore, it is possible requiire more than one variable.


  • sudo pip3 install xarray
  • sudo pip3 install netcdf4
import os
import xarray as xr
from pandas import concat, to_datetime
import copy

## extract datapoint from netcdf grid data
def datapointnc(lpath_input:list,lat:float,lon:float,lvars:list) -> 'df':
    Extract datapoint from netcdf grid data.
    lpath_input -- list of input paths of netcdf files.
    lat -- latitude of point to be extracted.
    lon -- longitude of point to be extracted.
    lvars -- list of vars to be extracted.
    return -- requested data.
    # loop of files
    for ifile,ipath_input in enumerate(lpath_input):
        # open data file
        ds = xr.open_dataset(ipath_input)
        # data selection
        dsloc = ds.sel(lon=lon,lat=lat,method='nearest')
        # loop of variables
        for ii,svar in enumerate(lvars):
                # variable data to df
                VAR = dsloc[svar].to_pandas().to_frame(name=svar)
                # concat
                if ii == 0: FILE = copy.deepcopy(VAR)
                else: FILE = concat([FILE,VAR],axis=1)
                # clean
                print('[warning] the variable "%s" is not available.'%svar)
        # append data
        if ifile==0: DATA = copy.deepcopy(FILE)
        else: DATA = DATA.append(FILE)
        # clean
        del(ds); del(dsloc); del(FILE)
    # format datetime index
    DATA.index = to_datetime(DATA.index)
    # return
    return DATA