【问题标题】:Indexing non-continous time-series from a dataset/datarray从数据集/数据数组索引非连续时间序列
【发布时间】:2019-04-11 11:46:17
【问题描述】:

我想从我的数据集中为我的时间序列中的相应值选择数据。时间序列中的日期不是连续的。所以,我不能使用带有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 数据帧,然后使用df.loc 方法有效,但对于大型数据集可能不太干净。所以,我想知道如何单独使用xarray 索引。
  • 您确定对由 DatetimeIndex 索引的 DataFrame 进行索引是否适用于字符串列表?使用 pandas 0.24.0 我似乎遇到了类似的错误。
  • 是的,我又检查了一遍。它可以使用 .loc 在 v 0.24.2 的 Pandas DataFrame 中将其索引为字符串
  • 是的,单个字符串可以工作(尽管这与将字符串转换为日期时间对象的含义略有不同。单个字符串可以表示日期范围;有关示例,请参见partial datetime string indexing)。据我所知,熊猫不会自动将字符串列表转换为日期时间对象,如下面的回答所示。
  • @spencerkclark 在链接中,他们没有使用.loc 方法。我再次检查,使用 dict 方法进行索引不适用于字符串列表,但如果字符串与 DateTimeIndex 的字符完全匹配,则使用 .loc 方法工作。

标签: python python-xarray


【解决方案1】:

我认为您需要先将字符串转换为日期时间对象。 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']))

【讨论】:

  • 我没有想到这很简单,谢谢
  • 你能把我链接到sel方法的代码吗?我想了解它在幕后所做的事情。我试图在 GitHub 上查找它,但我是新手,找不到它
  • 没问题,见here
猜你喜欢
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2020-08-19
  • 2013-06-03
  • 1970-01-01
  • 2021-06-17
  • 2016-09-06
相关资源
最近更新 更多