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

Why updating the elements in a Numpy array based on the elements from another array turns all values to zero?

Say I have two Numpy 1D arrays a and b of the same size.

import numpy as np
a = np.full(10, -10)
b = np.random.rand(10)
print(a)
# [-10 -10 -10 -10 -10 -10 -10 -10 -10 -10]
print(b)
# [0.8725654  0.48385524 0.67801994 0.30381863 0.95460565 0.73915384 0.38097293 0.4604181  0.91182102 0.33428477]

Now I want to update array a with the elements from array b based on some condition using a for loop, for example:

for i, x in enumerate(a):
    if x < b[i]:
        a[i] = b[i]
print(a)
# [0 0 0 0 0 0 0 0 0 0]

Why am I getting an array of all zeros instead of the values from array b?

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

>Solution :

If you use a = np.full(10, -10) the data type is int32. Thus the values you assign from array b are rounded to 0. Just use:

a = np.full(10, -10, dtype=float)

and its should work.

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