[英]Using 2d numpy mask np.where to address a 3d numpy array (pythonic??)
[英]Numpy masking 3D array using np.where() index
我根據幾個條件創建了一個索引
transition = np.where((rain>0) & (snow>0) & (graup>0) & (xlat<53.) & (xlat>49.) & (xlon<-114.) & (xlon>-127.)) #indexes the grids where there are transitions
具有(3,259711)的形狀,如下所示:
array([[ 0, 0, 0, ..., 47, 47, 47], #hour
[847, 847, 848, ..., 950, 950, 951], #lat gridpoint
[231, 237, 231, ..., 200, 201, 198]]) #lon gridpoint
我還有其他幾個變量(例如temp),它們的形狀分別是(48,1015,1359),對應於小時,緯度,經度。
看到索引是我的有效網格點,如何屏蔽所有變量(如temp),使其保留(48,1015,1359)形狀,但屏蔽索引外部的值。
In [90]: arr = np.arange(24).reshape(6,4)
In [91]: keep = (arr % 3)==1
In [92]: keep
Out[92]:
array([[False, True, False, False],
[ True, False, False, True],
[False, False, True, False],
[False, True, False, False],
[ True, False, False, True],
[False, False, True, False]], dtype=bool)
In [93]: np.where(keep)
Out[93]:
(array([0, 1, 1, 2, 3, 4, 4, 5], dtype=int32),
array([1, 0, 3, 2, 1, 0, 3, 2], dtype=int32))
簡單應用keep
遮罩即可得到所需值的一維數組。 我也可以使用where
元組建立索引。
In [94]: arr[keep]
Out[94]: array([ 1, 4, 7, 10, 13, 16, 19, 22])
使用keep
,或者說它是布爾逆,我可以創建一個掩碼數組:
In [95]: np.ma.masked_array(arr,mask=~keep)
Out[95]:
masked_array(data =
[[-- 1 -- --]
[4 -- -- 7]
[-- -- 10 --]
[-- 13 -- --]
[16 -- -- 19]
[-- -- 22 --]],
mask =
[[ True False True True]
[False True True False]
[ True True False True]
[ True False True True]
[False True True False]
[ True True False True]],
fill_value = 999999)
np.ma.masked_where(~keep, arr)
做同樣的事情-只是參數順序不同。 它仍然期望布爾掩碼數組。
我可以從where
元組開始做同樣的事情:
In [105]: idx = np.where(keep)
In [106]: mask = np.ones_like(arr, dtype=bool)
In [107]: mask[idx] = False
In [108]: np.ma.masked_array(arr, mask=mask)
在np.ma
類中可能有一個可以通過一次調用完成此操作的東西,但是它必須進行相同的構造。
這也適用:
x = np.ma.masked_all_like(arr)
x[idx] = arr[idx]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.