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 bina开发者_如何学Cry 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.
Y=X[0,:]+X[1,:]
D = ((1<Y) & (Y<2)).astype(int)
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?
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])
This?
bits = [ bool(low <= value < high) for value in some_list ]
Try using all
(edited to return int
):
D = numpy.all([1 < x, x < 2], axis=0).astype(int)
精彩评论