Modify a series of numpy arrays in place using boolean indexing

For a 2D numpy array, i.e.

import numpy as np data = np.array([ [11,12,13], [21,22,23], [31,32,33], [41,42,43], ]) 

I need to modify a sub-array based on two masking vectors for the required rows and columns;

 rows = np.array([False, False, True, True], dtype=bool) cols = np.array([True, True, False], dtype=bool) 

So that is;

 print data #[[11,12,13], # [21,22,23], # [0,0,33], # [0,0,43]] 
+7
source share
1 answer

Now that you know how to access the rows / columns you want, just assign the value you want for your subarray. This is a little trickier:

 mask = rows[:,None]*cols[None,:] data[mask] = 0 

The reason is that when we access the subarray as data[rows][:,cols] (as shown in the previous question, the previous question .

To create a mask, we could use the & operator instead of * (because we are dealing with boolean arrays) or the simpler np.outer :

 mask = np.outer(rows,cols) 

Edit: props @Marcus Jones for np.outer solution.

+5
source

All Articles