【问题标题】:xarray - select/index DataArray from the time labels from another DataArrayxarray - 从另一个 DataArray 的时间标签中选择/索引 DataArray
【发布时间】:2021-06-09 16:26:31
【问题描述】:

我有两个 DataArray 对象,分别称为“A”和“B”。

除了LatitudeLongitude,它们都有一个time 维度表示每日数据。 A 的时间坐标小于B

A的时间维度:

<xarray.DataArray 'time' (time: 1422)>
array(['2015-03-30T00:00:00.000000000', '2015-06-14T00:00:00.000000000',
       '2015-06-16T00:00:00.000000000', ..., '2019-08-31T00:00:00.000000000',
       '2019-09-01T00:00:00.000000000', '2019-09-02T00:00:00.000000000'],
      dtype='datetime64[ns]')
Coordinates:
  * time     (time) datetime64[ns] 2015-03-30 2015-06-14 ... 2019-09-02

B的时间维度:

<xarray.DataArray 'time' (time: 16802)>
array(['1972-01-01T00:00:00.000000000', '1972-01-02T00:00:00.000000000',
       '1972-01-03T00:00:00.000000000', ..., '2017-12-29T00:00:00.000000000',
       '2017-12-30T00:00:00.000000000', '2017-12-31T00:00:00.000000000'],
      dtype='datetime64[ns]')
Coordinates:
  * time     (time) datetime64[ns] 1972-01-01 1972-01-02 ... 2017-12-31

显然,A 的 time 维度是 B 的 time 维度的子集。我想使用 A 中的所有 time 标签从 B 中选择数据。由于 A 中的时间不连续,我认为 slice 不合适。所以我尝试使用sel

B_sel = B.sel(time=A.time)

我收到一个错误:KeyError: "not all values found in index 'time'"

【问题讨论】:

    标签: python pandas numpy python-xarray


    【解决方案1】:
    A_new = A.where(A.time.isin(B.time), drop=True)
    

    http://xarray.pydata.org/en/stable/user-guide/indexing.html

    【讨论】:

    • 在这种情况下,我认为每一行可读和清晰的解释,直接在这里,用英文散文,可能会让你赞成..... ;-)
    【解决方案2】:

    显然,A 的时间维度是 B 的时间维度的子集。

    我收到一个错误:KeyError:"not all values found in index 'time'"

    错误信息本身就暗示了陈述一中的假设是错误的。此外,如果您仔细查看您的时间值,A 的值直到 2019 年,而B 的值在 2017 年结束。

    所以,有两种方法可以解决这个问题:

    1. 如果您确定 A 在 2017 年之前具有 B 中的所有值,那么

      sel_dates = A.time.values[A.time.dt.year < 2017]
      B_sel = B.sel(time=sel_dates)
      
    2. 如果您不确定 A 中的值是否连续,因为某处存在一些意外值,那么您可以使用 np.isin() 执行逐元素检查,这是速度优化的 numpy 函数之一

      sel_dates = A.time.values[np.isin(A.time.values, B.time.values)]
      
       ## example ##
       ## dates1 is an array of daily dates of 1 month
       dates1 = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
       dates2 = np.array(['2005-02-03', '2002-02-05', '2000-01-05'], dtype='datetime64')
       # checking for dates2 which are a part of dates 1
       print(np.isin(dates2, dates1))
       >>array([ True, False, False])
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-15
      • 2019-01-18
      • 2017-09-15
      • 2021-07-14
      • 1970-01-01
      • 2021-02-02
      • 2019-06-28
      • 2020-10-26
      相关资源
      最近更新 更多