Replace the value in arrray by another aarray

Question:

I have a mask array: [0,0,0,0,1,1,0,0,1,1,0,1,0].
And a values array: [3,4,5,6,7]
Which is the best way that I can replace all value 1 in mask array into the values array?
Expected result: [0,0,0,0,3,4,0,0,5,6,0,7,0]
I am working with large array.

Asked By: Tran Trong Cuong

||

Answers:

You can use iterator:

mask = [0,0,0,0,1,1,0,0,1,1,0,1,0]
nums = iter([3,4,5,6,7])

output = [next(nums) if m else 0 for m in mask]

print(output) # [0, 0, 0, 0, 3, 4, 0, 0, 5, 6, 0, 7, 0]
Answered By: j1-lee

Assuming , and a values length equal to the number of 1s.

Use boolean indexing:

mask = np.array([0,0,0,0,1,1,0,0,1,1,0,1,0])
values = [3,4,5,6,7]

mask[mask==1] = values 

If values can be longer than the sum of 1s:

m = mask==1
mask[m] = values[:m.sum()]

Output:

array([0, 0, 0, 0, 3, 4, 0, 0, 5, 6, 0, 7, 0])
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.