Sher
Sher

Reputation: 415

How to drop unmatching time series from two xarray time-series dataset

I have two xarray dataset that have matching and unmatching time series. I would like to drop time series from dataset 2 that doesn't match with time-series of dataset 1.

ds1
    <xarray.Dataset>
    Dimensions:      (time: 149, x: 311, y: 266)
    Coordinates:
      * y            (y) float64 -3.256e+06 -3.256e+06 ... -3.263e+06 -3.263e+06
        spatial_ref  int32 3577
      * time         (time) datetime64[ns] 2016-01-01T00:09:15.704000 ... 2020-12...
      * x            (x) float64 1.913e+06 1.913e+06 1.913e+06 ... 1.92e+06 1.92e+06
    Data variables:
        FMCOB          (time, y, x) float64 78.63 48.68 85.0 ... 42.16 91.27 52.36
        Forest       (x, y) int64 0 0 0 3 3 3 3 3 0 0 0 0 ... 0 0 3 3 3 3 3 3 3 3 3
        Grass        (x, y) int64 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0
        Shrub        (x, y) int64 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0
    Attributes:
        crs:           EPSG:3577
        grid_mapping:  spatial_ref
        units:         % dry matter

ds2
<xarray.Dataset>
    Dimensions:      (time: 155, x: 76, y: 47)
    Coordinates:
      * y            (y) float64 -3.257e+06 -3.257e+06 ... -3.258e+06 -3.258e+06
        spatial_ref  int32 3577
      * time         (time) datetime64[ns] 2016-01-01T00:09:15.704000 ... 2020-12...
      * x            (x) float64 1.919e+06 1.919e+06 ... 1.921e+06 1.921e+06
    Data variables:
        FMCOB          (time, y, x) float64 81.67 87.5 74.4 95.0 ... nan 58.39 85.96
        Forest       (x, y) int64 0 0 0 0 0 0 3 3 3 3 3 3 ... 0 0 0 0 0 0 0 0 0 0 0
        Grass        (x, y) int64 0 0 1 1 1 1 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 0
        Shrub        (x, y) int64 0 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 2 0 0 0 0 2
    Attributes:
        crs:           EPSG:3577
        grid_mapping:  spatial_ref
        units:         % dry matter

What I tried is following:

for i in ds1.time:
    for k in ds2.time:
        if k!=i:
            
            ds2.drop_sel(time = np.datetime64(k))
            

But this throws following error:

ValueError                                Traceback (most recent call last)
<ipython-input-226-70fe5e9f97a4> in <module>
      4     for k in ds2.time:
      5         if k!=i:
----> 6             ds2.drop_sel(time = np.datetime64(k))

ValueError: Could not convert object to NumPy datetime   

Upvotes: 2

Views: 552

Answers (1)

Val
Val

Reputation: 7023

If you want to select all timeslices from ds2 which are also present in ds1 you can do

time_ix = np.isin(ds2.time, ds1.time)
ds2_sel = ds2.sel(time=time_ix)

where time_ix is a simple boolean array with True for each element in ds2.time that also occurs in ds1.time.

Upvotes: 4

Related Questions