I am trying to extract two variables values of a netCDF file at specific coordinates. From what I have seen from various posts on StackOverflow, the best way to achieve that is to work with arrays
.
I have tried to use this method but it does not work and I am struggling finding out why.
The code I used is the following:
import xarray as xr
file = "input.nc"
lon=24.2
lat=17.8
da = xr.open_dataset(file)
ts = da.sel(lon=lon, lat=lat, method="nearest") #I also tried da["variable1"].sel(lon=lon, lat=lat, method="nearest") but same outcome.
But it raised this error:
KeyError: 'lon is not a valid dimension or coordinate'
I then tried to set lon and lat as coordinates (da.set_coords(("lat", "lon"))
) but it still raised an error:
KeyError: 'no index found for coordinate lon'
I have very rarely worked with arrays so I don't understand what is wrong here. Here are more details of my netCDF:
xarray.Dataset
Dimensions: south_north: 63, west_east: 69, vcoord_dim: 8, Time: 25, bottom_top: 8
Coordinates: (0) # For some reasons lon and lat are Data variables and not Coordinates in this netCDF.
Data variables: (216)
I also tried a more mannual extraction method (validated answer here) but it gave an index value way out of bound for the j
that I can also not explain.
So, to summarize, what I want is extract the values of some Data variables
at specific lon/lat values for all the timesteps of the netCDF.
I looked everywhere for answers but nothing helped me understand what was wrong. Any tips and advices would be greatly appreciated.