简体   繁体   中英

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 ?

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.

koxx answer is right, but I also advise you to do this operation using numpy methods rather than a for loop. This code should give you the same output:

import numpy as np
a = np.full(10, 0.5)
b = np.random.rand(10)
a = np.maximum(a, b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM