Copy or view numpy subarms 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 both create a new subrange and change the selected elements in place based on two mask vectors for the required rows and columns;

 rows = [False, False, True, True] cols = [True, True, False] 

Thus,

 print subArray # [[31 32] # [41 42]] 
+5
source share
1 answer

First make sure your rows and cols are actually logical ndarrays and then use them to index your data

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

Explanation If you use a list of boolean elements instead of ndarray , numpy converts False/True to 0/1 and interprets this as the row / column indexes you want. When using bool ndarray you are actually using some specific NumPy mechanisms.

+4
source

All Articles