UPDATE: Following the comments below, I have updated the above script to get the col and row of a pixels and retunr the lat, lon and nc value.
def ExtractVarsFromNetcdf(x_coord, y_coord, ncdir, varnames):
"""
@params:
x_coord - Required : the x coordinate of the point
x_coord - Required : the y coordinate of the point
ncdir - Required : The directory of the netcdf file.
varnames - Required : The netcdf variables
"""
with Dataset(ncdir, "r") as nc:
# Get the nc lat and lon from the point's x, y
lon = nc.variables["lon"][int(round(x_coord))]
lat = nc.variables["lat"][int(round(y_coord))]
# Return a np.array with the netcdf data
nc_data = np.ma.getdata(
[nc.variables[varname][:, x_coord, y_coord] for varname in varnames]
)
return nc_data, lon, lat