How can I check in xarray if a coordinate exists?

Viewed 188

I want something similar to this: if fileObj.is_file() == True: But for a dataset. I want to check if a date exists befor I select it.

y_begin = 2007
y_end = 2020
begin_date = '05-01'
end_date = '09-31'
ds_so_merge = None

for y in range(y_begin, y_end +1):
    begin = str(y) + '-' + begin_date
    end = str(y) + '-' + end_date

!!!here checking if the date exists and if not trying the following date!!!

    ds_so = dataset.sel(time=slice(begin, end))
    if ds_so_merge is None:
        ds_so_merge = ds_so

    else:
        ds_so_merge = ds_so.merge(ds_so_merge)
1 Answers

you can check if a coordinate contains a specific value with value in coord just like you could with a numpy array or a pandas index.

Another option since you're using slices would just be to pull all elements which match the slice criteria, then select the first matched element.

Something like the following should work:

first_time_matching_slice = dataset.sel(time=slice(begin, end)).isel(time=0)
Related