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
CodePudding user response:
Try:
>>> [row for row in verts if row[2] >= 3 and row[2] < 7]
[[1, 2, 3], [4, 5, 6]]
CodePudding user response:
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]])