Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIlter 2d array using 1d boolean array [duplicate]

I have two numpy arrays.

x = [[1,2], [3,4], [5,6]]
y = [True, False, True]

I'd like to get the element of X of which corresponding element of y is True:

filtered_x = filter(x,y)
print(filtered_x) # [[1,2], [5,6]] should be shown.

I've tried np.extract, but it seems work only when x is 1d array. How do I extract the elements of x corresponding value of y is True?

like image 974
Light Yagmi Avatar asked Jul 16 '26 00:07

Light Yagmi


1 Answers

Just use boolean indexing:

>>> import numpy as np

>>> x = np.array([[1,2], [3,4], [5,6]])
>>> y = np.array([True, False, True])
>>> x[y]   # or "x[y, :]" because the boolean array is applied to the first dimension (in this case the "rows")
array([[1, 2],
       [5, 6]])

And in case you want to apply it on the columns instead of the rows:

>>> x = np.array([[1,2], [3,4], [5,6]])
>>> y = np.array([True, False])
>>> x[:, y]  # boolean array is applied to the second dimension (in this case the "columns")
array([[1],
       [3],
       [5]])
like image 80
MSeifert Avatar answered Jul 18 '26 14:07

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!