2

I have an array of ints, they need to be grouped by 4 each. I'd also like to select them based on another criterion, start < t < stop. I tried

data[group].reshape((-1,4))[start < t < stop]

but that complains about the start < t < stop because that's hardcoded syntax. Can I somehow intersect the two arrays from start < t and t < stop?

2
  • What are start, stop, and t? Is one or more of them supposed to take the values of some vector? Commented Dec 7, 2013 at 3:01
  • t is an array of numbers, start and stop are both numbers. Commented Dec 7, 2013 at 3:10

2 Answers 2

2

The right way of boolean indexing for an array should be like this:

>>> import numpy as np
>>> a=np.random.randint(0,20,size=24)
>>> b=np.arange(24)
>>> b[(8<a)&(a<15)] #rather than 8<a<15
array([ 3,  5,  6, 11, 13, 16, 17, 18, 20, 21, 22, 23])

But you may not be able to reshape the resulting array into a shape of (-1,4), it is a coincidence that the resulting array here contains 3*4 elements.

EDIT, now I understand your OP better. You always reshape data[group] first, right?:

>>> b=np.arange(96)
>>> b.reshape((-1,4))[(8<a)&(a<15)]
array([[12, 13, 14, 15],
       [20, 21, 22, 23],
       [24, 25, 26, 27],
       [44, 45, 46, 47],
       [52, 53, 54, 55],
       [64, 65, 66, 67],
       [68, 69, 70, 71],
       [72, 73, 74, 75],
       [80, 81, 82, 83],
       [84, 85, 86, 87],
       [88, 89, 90, 91],
       [92, 93, 94, 95]])
Sign up to request clarification or add additional context in comments.

Comments

2

How about this?

import numpy as np

arr = np.arange(32)
t = np.arange(300, 364, 2)
start = 310
stop = 352
mask = np.logical_and(start < t, t < stop)
print mask
print arr[mask].reshape((-1,4))

I did the masking before the reshaping, not sure if that's what you wanted. The key part is probably the logical_and().

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.