0

I have a numpy array of some dimension and I would like to make a slice of this array using a boolean array. For instance, given my array called 'verts' and I want to make a slice of this array into another array called 'upper' based on some condition. I can do the following:

cond_upper = verts[:,2]<L/2
upper = verts[cond_upper]

How can I modify the above snippet so that a double condition is satisfied, something like this:

cond_upper = verts[:,2]<L/2 and verts[:,2]<40.0
upper = verts[cond_upper]

This does not give me the desired result because python wants me to compare them element-wise, however this is not what I want to do. How can I resolve this?

I add an example to make things clearer:

verts = np.array([[1,2,3],
                  [4,5,6],
                  [7,8,9],])
cond = verts[:,2]>3 and verts[:,2]<7
upper = verts[cond]

Expected result:

upper = [[1,2,3],
         [4,5,6],]

I hope this makes it somewhat clearer

10
  • Can you update your code with a sample and the expected result please? Commented Oct 17, 2021 at 21:23
  • Not sure which array package you are using, but try & instead of and. Commented Oct 17, 2021 at 21:23
  • @corralien I added an edit Commented Oct 17, 2021 at 21:30
  • @mozway I get the following error when I use that: TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Commented Oct 17, 2021 at 21:31
  • @mozway It works fine, I googled a little bit and I found out I needed to put some brackets. Can you post it as an answer so I can accept it? Commented Oct 17, 2021 at 21:36

2 Answers 2

2

Try:

>>> [row for row in verts if row[2] >= 3 and row[2] < 7]
[[1, 2, 3], [4, 5, 6]]
Sign up to request clarification or add additional context in comments.

Comments

1

You should use the bitwise operator & for element comparisons, not and.

import numpy as np
verts = np.array([[1,2,3],
                  [4,5,6],
                  [7,8,9],])
cond = (verts[:,2]>=3) & (verts[:,2]<7)
upper = verts[cond]

Output:

array([[4, 5, 6]])

6 Comments

Check your code... If it's not a numpy array, it can't work!
OP mentioned the input was an array, I added the import for clarity ;)
Indeed I use a numpy array and the answer submitted by @mozway works fine. I should have added in the question that I am using a numpy array. I have properly edited the question now
Missing parenthesis: cond = (verts[:,2]>3) & (verts[:,2]<7)
And the filter don't give the expect output because 3 > 3 is not True. 3 >= 3 is True
|

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.