I would like to substitute the '1's on an array nparray1 = np.array([1, 1, 0, 0, 1])
by the values on another array nparray2 = np.array([8,7,4])
, to produce nparray1 = np.array([8, 7, 0, 0, 4])
.
I was hoping to do this as efficiently as possible, hence I thought using a list comprehension would be the best alternative, however, I am unable to find a way to do this. The alternative for loop would look like:
nparray1 = np.array([1, 1, 0, 0, 1])
nparray2 = np.array([8,7,4])
for i in range(len(nparray1)):
if nparray1[i]==True:
nparray1[i] = nparray2[0]
nparray2 = nparray2[1:]
CodePudding user response:
You can use:
nparray1[nparray1 == 1] = nparray2
print(nparray1)
# Output
array([8, 7, 0, 0, 4])
CodePudding user response:
Alternatively, I think you can also keep track of an idx variable which you only increment when you see a 1 in the first numpy array.
nparray1 = np.array([1, 1, 0, 0, 1])
nparray2 = np.array([8,7,4])
idx = 0;
for i in range(len(nparray1)):
if nparray1[i] == 1:
nparray1[i] = nparray1[i] * nparray2[idx]
idx =1
print(nparray1)
or alternatively, via the use of iter()
:
nparray1 = numpy.array([1, 1, 0, 0, 1])
nparray2 = iter(numpy.array([8,7,4]))
for i in range(len(nparray1)):
if nparray1[i]== 1:
nparray1[i] = next(nparray2)
print(nparray1)