2

I have a numpy array similar to:

a = np.array([1,1,1],
             [1,1,1],
             [2,1,1],
             [2,3,1],
             [2,3,1],
             [2,3,1],
             [3,4,1],
             [3,4,1],
             [3,4,1],
 ])

and would like to extract the rows where

a[0,:] >=2 and a[1,:] < 4 

into b, resulting in:

b = np.array([2,1,1],
             [2,3,1],
             [2,3,1],
             [2,3,1],
 ])

I tried with

b = a[(a[0,:] >=2) & (a[1,:] < 4 )]

and

b = a[np.where((a[0,:] >=2) & (a[1,:] < 4 ))]

but that does not work. Any ideas?

Thanks! Jorge

3
  • 2
    a[0,:] is the first row. Did you want the first column? The first column is a[:, 0]. Commented Nov 13, 2015 at 18:34
  • ah, that's it, basic mistake and could not spot it, sorry. thanks! Commented Nov 13, 2015 at 18:42
  • When debugging, I like to look at that inner boolean mask. It's usually more productive to dig down and look at the pieces, rather than throw another layer of calculation on (e.g. the where). Commented Nov 13, 2015 at 19:07

2 Answers 2

4

Your condition is using the first and second row of a, rather than the first and second column. a[:, n] selects the nth column, so you want

b = a[(a[:, 0] >= 2) & (a[:, 1] < 4)]
Sign up to request clarification or add additional context in comments.

1 Comment

exactly what I needed. Thanks!
0

I don't know how to do it in one step but you can do

b = a[a[:,0]>=2]
c = b[b[:,1]<4]

print c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.