Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign zeros to minimum values in numpy 3d array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.        ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading