Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy or view numpy subarray using boolean indexing

Tags:

python

numpy

Given 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 sub-array or modify the selected elements in place based on two masking vectors for the desired rows and columns;

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

Such that

print subArray

# [[31 32]
#  [41 42]]
like image 300
Marcus Jones Avatar asked Oct 06 '22 15:10

Marcus Jones


1 Answers

First, make sure that your rows and cols are actually boolean ndarrays, 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 booleans instead of an ndarray, numpy will convert the False/True as 0/1, and interpret that as indices of the rows/cols you want. When using a bool ndarray, you're actually using some specific NumPy mechanisms.

like image 154
Pierre GM Avatar answered Oct 10 '22 03:10

Pierre GM