4

Say I have an xarray DataArray. One of the Dimensions is a time dimension:

import numpy as np
import xarray as xr
import pandas as pd

time = pd.date_range('1980-01-01', '2017-12-01', freq='MS')
time = xr.DataArray(time, dims=('time',), coords={'time':time})

da = xr.DataArray(np.random.rand(len(time)), dims=('time',), coords={'time':time})

Now if I only want the years from 1990 to 2000, what I can do is easy:

da.sel(time=slice('1990', '2000'))

But what if I want to drop these years? I want the data for all years except those.

da.drop_sel(time=slice('1990', '2000'))

fails with

TypeError: unhashable type: 'slice'

What's going on? What's the proper way to do that?

At the moment, I'm creating a new DataArray:

tdrop = da.time.sel(time=slice('1990', '2000'))
da.drop_sel(time=tdrop)

But that seems unnecessary convoluted.

chw21
  • 7,970
  • 1
  • 16
  • 31

1 Answers1

2

What about using where with the drop optional parameter set to True to filter on the year? Using the example below, the data with 1990 <= year <= 2000 would be dropped.

da = da.where((da["time.year"] < 1990) | (da["time.year"] > 2000), drop=True)
dspencer
  • 4,297
  • 4
  • 22
  • 43
  • 1
    Thank you. I want to add that I only recently noticed that the `drop_sel` method is quite young at this point, so maybe the functionality will still be added. Anyway, here's your bounty. – chw21 Mar 17 '20 at 20:33