I have a boolean mask array a
of length n
:
a = np.array([True, True, True, False, False])
I have a 2d array with n
columns:
b = np.array([[1,2,3,4,5], [1,2,3,4,5]])
I want a new array which contains only the "True"-values, for example
c = ([[1,2,3], [1,2,3]])
c = a * b
does not work because it contains also "0" for the false columns what I don't want
c = np.delete(b, a, 1) does not work
Any suggestions?
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
Boolean masking, also called boolean indexing, is a feature in Python NumPy that allows for the filtering of values in numpy arrays.
A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.
We can also index NumPy arrays using a NumPy array of boolean values on one axis to specify the indices that we want to access. This will create a NumPy array of size 3x4 (3 rows and 4 columns) with values from 0 to 11 (value 12 not included).
You probably want something like this:
>>> a = np.array([True, True, True, False, False]) >>> b = np.array([[1,2,3,4,5], [1,2,3,4,5]]) >>> b[:,a] array([[1, 2, 3], [1, 2, 3]])
Note that for this kind of indexing to work, it needs to be an ndarray
, like you were using, not a list
, or it'll interpret the False
and True
as 0
and 1
and give you those columns:
>>> b[:,[True, True, True, False, False]] array([[2, 2, 2, 1, 1], [2, 2, 2, 1, 1]])
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