[英]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.