3

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?

3
  • 1
    x[y]. It's called boolean indexing. Commented Sep 1, 2017 at 13:06
  • You can try using a list comprehension like [val for val in x if y[x.index(val)]]. Simple and elegant. Commented Sep 1, 2017 at 13:22
  • @AsadMoosvi and slower than numpy built in functions, and also does not return a np.array... Commented Sep 1, 2017 at 14:14

2 Answers 2

10

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

For consistency and clarity, I prefer x[y, :] and x[:, y]
I tend to prefer to omit trailing , : because it's more to type and the result doesn't differ if I include them or omit them. But I can see where it's easier to understand. :)
0

l=[x[i] for i in range(0,len(y)) if y[i]] this will do it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.