[英]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.in1d
和np.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.where
和np.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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.