如何使用numpy将除前n个值之外的所有矩阵值(2D数组)归零?

2024-04-20 11:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个2D numpy数组。给定n,我想把矩阵中除前n以外的所有元素都加上

我试过idx = (-y_pred).argsort(axis=-1)[:, :n]确定最大n值的索引是什么,但是idx形状是[H,W,n],我不明白为什么。你知道吗

我试过-

sorted_list = sorted(y_pred, key=lambda x: x[0], reverse=True)
top_ten = sorted_list[:10]

但它并没有真正返回前十大指数。你知道吗

有没有一种有效的方法来找出前n个指数,然后把其余的归零?你知道吗

编辑 输入是一个NxM值矩阵,输出是大小为NxM的相同矩阵,因此除了对应于前10个值的索引外,所有值都是0


Tags: lambdakeynumpy元素矩阵数组指数list
2条回答

基于How do I get indices of N maximum values in a NumPy array?的思想,这里有一种使用^{}的方法

# sample input to work with
In [62]: arr = np.random.randint(0, 30, 36).reshape(6, 6)

In [63]: arr
Out[63]: 
array([[ 8, 25, 12, 26, 21, 29],
       [24, 22,  7, 14, 23, 13],
       [ 1, 22, 18, 20, 10, 19],
       [26, 10, 27, 19,  6, 28],
       [17, 28,  9, 13, 11, 12],
       [18, 25, 15, 29, 25, 25]])


# initialize an array filled with zeros
In [59]: nullified_arr = np.zeros_like(arr)
In [64]: top_n = 10

# get top_n indices of `arr`
In [57]: top_n_idxs = np.argpartition(arr.reshape(-1), -top_n)[-top_n:]

# copy `top_n` values to output array
In [60]: nullified_arr.reshape(-1)[top_n_idxs] = arr.reshape(-1)[top_n_idxs]


In [71]: nullified_arr
Out[71]: 
array([[ 0, 25,  0, 26,  0, 29],
       [ 0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0],
       [26,  0, 27,  0,  0, 28],
       [ 0, 28,  0,  0,  0,  0],
       [ 0,  0,  0, 29, 25, 25]])

下面的代码将使NxM矩阵X无效。你知道吗

threshold = np.sort(X.ravel())[-n]  # get the nth largest value
idx = X < threshold
X[idx] = 0

注意:当存在重复值时,此方法可以返回包含多于n个非零元素的矩阵。你知道吗

相关问题 更多 >