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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With