1

Firstly, I have a compressed numpy array c and a mask m that was used to generate c from a full array a.

I want to output a reconstructed array b of the same shape as the original array a, but with the results from the compressed array. The following code works for this, but I don't know how to make it efficient. Any guidance will be appreciated

import numpy as np
a = np.asarray((1, 2, 3, 4, 5, 6, 7, 8, 9))
m = np.array((True,True,True,True,False,False,True,True,True))
c = np.ma.compressed(np.ma.masked_where(m==False, a))

i=0
j=0
b = np.zeros(a.size)
while (i<a.size):
    if (m[i] == True):
        b[i] = c[j]
        j = j+1
    i = i+1
b

which results in:

array([1., 2., 3., 4., 0., 0., 7., 8., 9.])
Tania
  • 418
  • 3
  • 20

2 Answers2

2

You can use boolean indexing:

b = np.zeros_like(m, dtype=float) # change dtype to `int` if that's what you want.

b[m] = c

Output

array([1., 2., 3., 4., 0., 0., 7., 8., 9.])
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

Can you just try,

b = a*m

This should give you the desired output.

Nik P
  • 224
  • 1
  • 5
  • 2
    Here I thought your question is how to construct `b` from `c` and `m`. – Quang Hoang Apr 15 '20 at 18:21
  • This works exactly as needed, and just in a line!!! Thanks a lot. – Tania Apr 15 '20 at 18:21
  • 1
    @Tania Please edit your question to accepted answer. Your original question asked to reconstruct using `c` and `m`. Maybe you want to replace masked elements with `0` instead. – Ehsan Apr 15 '20 at 18:33
  • Hi, not exactly, I was given just c and m. So there is no way to access a, and replace the masked elements. – Tania Apr 15 '20 at 18:37