[英]xarray - select/index DataArray from the time labels from another DataArray
我有两个 DataArray 对象,称为“ A
”和“ B
”。
除了Latitude
和Longitude
,它们都有一个表示每日数据的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'"
A_new = A.where(A.time.isin(B.time), drop=True)
显然,A 的时间维度是 B 时间维度的子集。
我收到一个错误:KeyError:“并非在索引‘时间’中找到所有值”
错误消息本身就暗示语句一中的假设是错误的。 此外,如果您仔细查看您的时间值, A
值直到 2019 年,而B
值在 2017 年结束。
所以,有两种方法可以解决这个问题:
如果您确定 A 在 2017 年之前具有 B 中的所有值,那么
sel_dates = A.time.values[A.time.dt.year < 2017] B_sel = B.sel(time=sel_dates)
如果您不确定 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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.