piRSquared
piRSquared

Reputation: 294526

reverse effects of boolean masking in numpy

Setup

np.random.seed(314)
x = np.random.rand(10, 4)
mask np.array([True, False, False, True])

x

array([[ 0.91687358,  0.58854191,  0.26504775,  0.78320538],
       [ 0.91800106,  0.82735501,  0.72795148,  0.26048042],
       [ 0.9117634 ,  0.26075656,  0.76637602,  0.26153114],
       [ 0.12229137,  0.38600554,  0.84008124,  0.27817936],
       [ 0.06991369,  0.63310965,  0.58476603,  0.58123194],
       [ 0.6772054 ,  0.6871551 ,  0.43892737,  0.3209265 ],
       [ 0.57055222,  0.47984862,  0.86107434,  0.83480474],
       [ 0.10576611,  0.06040804,  0.59688219,  0.79239497],
       [ 0.22635574,  0.5352008 ,  0.13606616,  0.37224445],
       [ 0.15197674,  0.42982185,  0.79270622,  0.40695651]])

I can mask x like so:

y = x[:, mask]
y

array([[ 0.91687358,  0.78320538],
       [ 0.91800106,  0.26048042],
       [ 0.9117634 ,  0.26153114],
       [ 0.12229137,  0.27817936],
       [ 0.06991369,  0.58123194],
       [ 0.6772054 ,  0.3209265 ],
       [ 0.57055222,  0.83480474],
       [ 0.10576611,  0.79239497],
       [ 0.22635574,  0.37224445],
       [ 0.15197674,  0.40695651]])

Question

given y and mask how do I generate:

array([[ 0.91687358,  0.        ,  0.        ,  0.78320538],
       [ 0.91800106,  0.        ,  0.        ,  0.26048042],
       [ 0.9117634 ,  0.        ,  0.        ,  0.26153114],
       [ 0.12229137,  0.        ,  0.        ,  0.27817936],
       [ 0.06991369,  0.        ,  0.        ,  0.58123194],
       [ 0.6772054 ,  0.        ,  0.        ,  0.3209265 ],
       [ 0.57055222,  0.        ,  0.        ,  0.83480474],
       [ 0.10576611,  0.        ,  0.        ,  0.79239497],
       [ 0.22635574,  0.        ,  0.        ,  0.37224445],
       [ 0.15197674,  0.        ,  0.        ,  0.40695651]])

Upvotes: 1

Views: 401

Answers (1)

piRSquared
piRSquared

Reputation: 294526

Solution

z = np.zeros((y.shape[0], len(mask)))
z[:, mask] = y

z

array([[ 0.91687358,  0.        ,  0.        ,  0.78320538],
       [ 0.91800106,  0.        ,  0.        ,  0.26048042],
       [ 0.9117634 ,  0.        ,  0.        ,  0.26153114],
       [ 0.12229137,  0.        ,  0.        ,  0.27817936],
       [ 0.06991369,  0.        ,  0.        ,  0.58123194],
       [ 0.6772054 ,  0.        ,  0.        ,  0.3209265 ],
       [ 0.57055222,  0.        ,  0.        ,  0.83480474],
       [ 0.10576611,  0.        ,  0.        ,  0.79239497],
       [ 0.22635574,  0.        ,  0.        ,  0.37224445],
       [ 0.15197674,  0.        ,  0.        ,  0.40695651]])

Upvotes: 2

Related Questions