Вот один из подходов, использующий numpy.argpartition()
, основанный на идее Как получить индексы N максимальных значений в массиве NumPy?
# 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]])