find indices x,y of a matrix of specific values in python

1.4k views Asked by At

I convert a list of integers to a two dimensinal array like this:

data = numpy.array( l )
shape = ( 10, 30 )
data = data.reshape( shape )

I try to get the indices x,y of the matrix of the values that are bigger than some threshold and lower than some other threshold.

I tried to make the next but it provides some errors:

data_indices = numpy.where(data<=obj_value_max and data>=obj_value_min) 

The error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

1

There are 1 answers

4
wflynny On BEST ANSWER

You need to change your where line to something like:

data_indices = numpy.where((data<=obj_value_max) & (data>=obj_value_min))

Notice the ()s around each conditional clause and the use of & (meaning "and"). This works because in numpy, <,<=,>,>=,&,|,... are overridden, i.e. they act differently than in native python. and and or cannot be overridden, and this is why you get the error message you get.

To get pairs of indices for each value (instead of (array of x indices, array of y indices)), do

zip(*data_indices)