9

The context: I have a netCDF with 30 years of (daily) data. I would like to select data across years for specific months, e.g. every May to March period.

I could do it with a separate function for selection, but I'm hoping there's a straightforward way to do it with xarray. The version I have installed is 0.9.6

2
  • What do you mean by "straightforward way"? I am thinking that xarray is not CDO or NCO, where you can just give an operator and you get a result what you want. With Python script, you have to work for your output - initialize new file with all necessary variables/dimensions, cut the data that you need, write selected data. Perhaps with cdo/nco you get what you want with much smaller effort.
    – msi_gerva
    Sep 28, 2018 at 10:16
  • "What do you mean by 'straightforward way' - One example would be the resample method (xarray.pydata.org/en/stable/generated/…) which allows you to select samples across the time series over a variety of time frames - that's an example of a built-in method that could be used to simplify a common task. Now for what I'm after I could of course accomplish what I'm after using apply and my own function - I said as much in the body of my question. You're welcome to write an answer if you have any other suggestions than that approach. Sep 28, 2018 at 11:23

1 Answer 1

19

If your time dimension is a datetime object, you can use the DatetimeAccessor object to select only the months you'd like:

# select only daily data from June, July, and August
da_jja_only = ds.sel(time=ds.time.dt.month.isin([6, 7, 8]))
2
  • I had to update to the latest version of xarray (0.10.9), but resolved my issue. Oct 1, 2018 at 6:50
  • da_jja_only = ds.sel(datetime=ds.datetime.dt.month.isin([6, 7, 8])) works for me. Thanks for the clue!
    – Ying
    Oct 27, 2020 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.