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

How to zero particular elements using a mask in python?

I ran into a simple problem, where I wanted to assign values according to a mask that represents a position of elements in an array. For instance array[*,1] = 0 but this code obviously would not work.

After a little thought I have come up with this:

import numpy as np

a = np.random.normal(size=(5, 2))

print(a)
print(a.shape)

for i in np.arange(a.shape[0]):
    a[i][1] = 0
    
print(a)
print(a.shape)

But obviously, this awkward loop is not a pythonic way of doing that.

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

So, can you share some neat ways of performing such operations in Python?

>Solution :

Just slice the array with a[:, 1] = 0 if you want all entries of the first column to be zero.

If you want to use a condition statement look into np.where, which can be used to index the array according to a[np.where(condition)] = 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