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?
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]])
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