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?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Light Yagmi
  • 5,085
  • 12
  • 43
  • 64

2 Answers2

11

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]])
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 4
    For consistency and clarity, I prefer x[y, :] and x[:, y] – Jblasco Sep 01 '17 at 13:11
  • 2
    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. :) – MSeifert Sep 01 '17 at 13:13
0

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

Vineet Jain
  • 1,515
  • 4
  • 21
  • 31