Assign zeros to minimum values in numpy 3d array

Question:

I have a numpy array of shape (100, 100, 20) (in python 3)

I want to find for each ‘pixel’ the 15 channels with minimum values, and make them zeros (meaning: make the array sparse, keep only the 5 highest values).

Example:

input: array = [[1,2,3], [7,6,9], [12,71,3]], num_channles_to_zero = 2

output: [[0,0,3], [0,0,9], [0,71,0]]

How can I do it?

what I have for now:

array = numpy.random.rand(100, 100, 20) 
inds = numpy.argsort(array, axis=-1) # also shape (100, 100, 20)

I want to do something like

array[..., inds[..., :15]] = 0

but it doesn’t give me what I want

Asked By: gozi

||

Answers:

np.argsort outputs indices suitable for the [...]_along_axis functions of numpy. This includes np.put_along_axis:

import numpy as np

array = np.random.rand(100, 100, 20) 
print(array[0,0])
#[0.44116124 0.94656705 0.20833932 0.29239585 0.33001399 0.82396784
# 0.35841905 0.20670957 0.41473762 0.01568006 0.1435386  0.75231818
# 0.5532527  0.69366173 0.17247832 0.28939985 0.95098187 0.63648877
# 0.90629116 0.35841627]

inds = np.argsort(array, axis=-1)
np.put_along_axis(array, inds[..., :15], 0, axis=-1)
print(array[0,0])
#[0.         0.94656705 0.         0.         0.         0.82396784
# 0.         0.         0.         0.         0.         0.75231818
# 0.         0.         0.         0.         0.95098187 0.
# 0.90629116 0.        ]
Answered By: André

As it mentioned in the numpy documentation

From each row, a specific element should be selected. The row index is just [0, 1, 2] and the column index specifies the element to choose for the corresponding row, here [0, 1, 0]. Using both together the task can be solved using advanced indexing:

>>>x = np.array([[1, 2], [3, 4], [5, 6]])
>>>x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

So, for your example:

a = np.array([[1,2,3], [7,6,9], [12,71,3]])
amax = a.argmax(axis=-1)
a[np.arange(a.shape[0]), amax] = 0
a
array([[ 1,  2,  0],
       [ 7,  6,  0],
       [12,  0,  3]])
Answered By: Ivan Pavlov
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.