Copy Or View Numpy Subarray Using Boolean Indexing
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 ne
Solution 1:
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.
Post a Comment for "Copy Or View Numpy Subarray Using Boolean Indexing"