Home > Blockchain >  Replace the value in arrray by another aarray
Replace the value in arrray by another aarray

Time:08-25

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.

CodePudding user response:

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])

CodePudding user response:

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]
  • Related