Light_B
Light_B

Reputation: 1800

Indexing non-continous time-series from a dataset/datarray

I want to select data from my dataset for the corresponding values in my time-series. The dates in the time series are not-continous. So, I can't use slice with sel. Here is how the index of my dataset looks like

ds.indexes
>longitude:Float64Index
>time: DatetimeIndex

For a Pandas data frame, if I had a time-based index then I could simply use label-based indexing like

df.loc[['1979-01-09 00:00:00', '1979-01-09 06:00:00']]

Xarray indexing is based on Pandas but I don't know how to implement the above approach

ds.var1.loc[['1979-01-09 00:00:00', '1979-01-09 06:00:00']]
>KeyError: "not all values found in index 'time'"

I also tried:

ds.var1.sel(dict(time=('1979-01-09 00:00:00', '1979-01-09 06:00:00')))
>TypeError: Cannot convert input [('1979-01-09 00:00:00', '1979-01-09 06:00:00')] of type <class 'tuple'> to Timestamp

It would be great to know how I can make this work both with .loc and sel method

Upvotes: 0

Views: 687

Answers (1)

spencerkclark
spencerkclark

Reputation: 2097

I think you'll need to convert the strings to datetime objects first. pandas.to_datetime should do the trick:

import pandas as pd
import xarray as xr

times = pd.date_range('2000-01-01', periods=3, freq='MS')
da = xr.DataArray(range(3), coords=[times], dims=['time'], name='a')
result = da.sel(time=pd.to_datetime(['2000-01-01', '2000-03-01']))

Upvotes: 2

Related Questions