从 dataset/datarray 索引非连续时间序列

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

我想从我的数据集中 select 数据获取我的时间序列中的相应值。时间序列中的日期不连续。所以,我不能将 slice 与 sel 一起使用。这是我的数据集索引的样子

ds.indexes
>longitude:Float64Index
>time: DatetimeIndex

对于 Pandas 数据框,如果我有一个基于时间的索引,那么我可以简单地使用基于标签的索引,例如

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

Xarray 索引基于 Pandas 但我不知道如何实现上述方法

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

我也试过:

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

很高兴知道如何使用 .locsel 方法来完成这项工作

我认为您需要先将字符串转换为日期时间对象。 pandas.to_datetime 应该可以解决问题:

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']))