Reputation: 2785
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
?
Upvotes: 0
Views: 81
Reputation: 587
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)
Upvotes: 1
Reputation: 367
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.
Upvotes: 2