drop_sel does not accept slice

Viewed 482

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.

1 Answers

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)
Related