Reed Richards
Reed Richards

Reputation: 4378

How to detect if the values in array are in a certain range and return a binary array in Python?

So I am trying to detect if the values in an array is in a certain range and then return a binary logical array i.e. one for true and zero for false. I have this but iPython keeps complaining

D = ( 1 < X[0,:] + X[1,:]) < 2 ).astype(int)

the interesting thing is that just checking one way works totally ok

D = ( X[0,:] + X[1,:]) < 2 ).astype(int)

which I find a bit perplexing.

Upvotes: 2

Views: 184

Answers (5)

Steve Tjoa
Steve Tjoa

Reputation: 61044

Try using all (edited to return int):

D = numpy.all([1 < x, x < 2], axis=0).astype(int)

Upvotes: 0

Josef
Josef

Reputation: 22897

unutbu's is shorter, this is more explicit

>>> import numpy
>>> numpy.logical_and(1 < np.arange(5), np.arange(5)< 4).astype(int)
array([0, 0, 1, 1, 0])

Upvotes: 1

unutbu
unutbu

Reputation: 879501

Y=X[0,:]+X[1,:]
D = ((1<Y) & (Y<2)).astype(int)

Upvotes: 2

S.Lott
S.Lott

Reputation: 391854

This?

 bits = [ bool(low <= value < high) for value in some_list ]

Upvotes: 0

Mariusz Lotko
Mariusz Lotko

Reputation: 384

array = (1, 2, 3, 4, 5)
bit_array = map(lambda x: 1 < x < 5 and 1 or 0, array)

bit_array is [0, 1, 1, 1, 0] after that. Is that what you wanted?

Upvotes: 1

Related Questions