[英]How can I change elements row-wise in a NumPy array based on several conditions
如果在特定索引 position (例如每行中的第二個元素)中找到該值並且該值小於指定的閾值,我想將 2D 數組的每一行中的最大值替換為 0。 到目前為止,這是我的代碼:
import numpy as np
arr = np.array([[1, 5, 3, 3],
[5, 6, 9, 3],
[2, 9, 3, 3],
[1, 4, 2, 2]])
output = np.where((arr == np.amax(arr[:,1]) & (arr < 7)), 0, arr)
在arr
中,索引 position 1 處的每個元素都應更改為 0,但前提是它是行中的最大值並且小於 7(例如)。 output 陣列還應在所有其他位置保持原始值。 我想得到的 output 看起來像這樣:
np.array([[1, 0, 3, 3],
[5, 6, 9, 3],
[2, 0, 3, 3],
[1, 0, 2, 2]])
任何幫助,將不勝感激。
編輯:要對NxM
矩陣進行概括,有必要在 col_mask 部分將len(arr)
更改為col_mask
arr.shape[1]
。 我將此添加到代碼中。
作為評論,結果應該是:
np.array([[1, 0, 3, 3],
[5, 6, 9, 3],
[2, 9, 3, 3],
[1, 0, 2, 2]])
9 in (2,1) 因為這高於閾值。
我會使用掩碼來檢查條件發生的位置來解決這個問題:
代碼的簡短版本:
arr = np.array([[1, 5, 3, 3],
[5, 6, 9, 3],
[2, 9, 3, 3],
[1, 4, 2, 2]])
thresh = 7 #threshold of value only put 0 if max y lower than this
col = 1 #only put 0 if maximum ocurrs in this column
max_vals = np.max(arr,1,keepdims=True) #get max values
maximum_as_bool = arr == max_vals #create a bool mask where of every max
col_mask = np.zeros(arr.shape[1],dtype=np.bool)
col_mask[col] = True #mask of columns values
thresh_mask = max_vals<thresh #mask for threshold
all_conditions = maximum_as_bool*thresh_mask*col_mask
arr[all_conditions ]=0 #combine masks
部分解釋:
max_vals = np.max(arr,1,keepdims=True) #get max values
maximum_as_bool = arr == max_vals #create a bool mask where of every max
結果是:
max_vals = [[5],
[9],
[9],
[4]]
maximum_as_bool = [[False, True, False, False],
[False, False, True, False],
[False, True, False, False],
[False, True, False, False]]
thresh = 7 #threshold of value only put 0 if max y lower than this
col = 1 #only put 0 if maximum ocurrs in this column
col_mask = np.zeros(arr.shape[1],dtype=np.bool)
col_mask[col] = True #mask of columns values
thresh_mask = max_vals<thresh #mask for threshold
至尊輸出:
col_mask = [False, False, False, False]
thresh_mask = [[ True],
[False],
[False],
[ True]]
最后,結合 al 掩碼以獲得所有條件都滿足的位置,然后將此值設置為 0:
all_conditions = maximum_as_bool*thresh_mask*col_mask
arr[all_conditions ]=0 #combine masks
至尊輸出
all_conditions = [[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]]
arr = [[1, 0, 3, 3],
[5, 6, 9, 3],
[2, 9, 3, 3],
[1, 0, 2, 2]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.