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):
try:
# 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
del(VAR)
except:
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