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

Cannot change Numpy array elements filtered by boolean indexing

Reproducible code:

x = np.array([0.9, 0.9, 1])
y = np.array([0, 0, 1])
y[x<1] = 1 - x[x<1]
print(y)

Output

array([0, 0, 1])

Desired output

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

array([0.1, 0.1, 1])

I know np.where will get me the desired output. I’m just curious about why boolean indexing doesn’t work in this case.

>Solution :

You must specify the dtype for y:

y = np.array([0, 0, 1], dtype=np.float64)

When you did not specify that, it assume integer as dtype. So each modification on this will be converted to original dtype of this array.

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