簡體   English   中英

替換滿足特定閾值的python ndarray的值

[英]Replacing values of a python ndarray satisfying certain threshold

我想將某個特定閾值之內的巨大python ndarray的值替換為0。說在[-0.1 and 0.1]的閾值之內。 最有效的方法是什么? 這是一個相當大的數組:

>>>np.shape(np_w)
shape=(1, 1, 1024, 1024) dtype=float32

我知道我們這里沒有Matlab的ismember ,但是,在搜索numpy文檔時,我發現了np.in1dnp.isin 到目前為止,我的解決方案看起來並不好且緩慢:

import numpy as np
Threshhold=X

res=np.isin(np_w,np_w[(np_w>=-Threshhold) & (np_w<=Threshhold)])
indicesToReplace=np.where(res)
np_w[indicesToReplace]=0

我個人將使用np.wherenp.logical_and的組合。

>>> import numpy as np
>>> threshold = 0.5
>>> my_arr = np.random.randn(20)
>>> my_arr
array([-0.28094279,  1.28432282,  0.2585762 ,  0.41902366,  1.21350506,
       -0.40586786, -1.04135578, -1.06168061,  0.25554365, -0.75404457,
        1.4755498 , -0.14902854,  0.15225808,  0.03667505,  0.6158351 ,
        0.05171262,  1.09116325, -0.5897306 , -0.69801693, -0.31560829,
       -0.36665813, -0.98115761,  1.21050881,  0.66356061, -0.03960144])
>>> my_arr[np.where(np.logical_and(np.greater(my_arr, -threshold), np.less(my_arr, threshold)))[0]] = np.nan
>>> my_arr
array([        nan,  1.28432282,         nan,         nan,  1.21350506,
               nan, -1.04135578, -1.06168061,         nan, -0.75404457,
        1.4755498 ,         nan,         nan,         nan,  0.6158351 ,
               nan,  1.09116325, -0.5897306 , -0.69801693,         nan,
               nan, -0.98115761,  1.21050881,  0.66356061,         nan])

如果它是一個大約為0的對稱間隔,則可以使用abs<布爾數組索引 (類似於整數數組索引,但是在這種情況下,您不需要在np.where周圍使用np.where ):

my_np[abs(my_np) <= treshhold] = 0

這會將絕對值小於或等於閾值的所有值替換為0

如果您需要更通用的解決方案,比如說下閾值的絕對值不等於上限閾值,那么您可以使用&組合表達式:

my_np[(my_np >= lower_treshhold) & (my_np <= upper_threshhold)] = 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM