Void
Void

Reputation: 153

Python: compare an array element-wise with a float

I have an array A=[A0,A1], where A0 is a 4x3 matrix, A1 is a 3x2 matrix. I want to compare A with a float, say, 1.0, element-wise. The expected return B=(A>1.0) is an array with the same size as A. How to achieve this?

I can copy A to C and then reset all elements in C to be 1.0, then do a comparison, but I think python (numpy/scipy) must have a smarter way to do this... Thanks.

Upvotes: 1

Views: 5736

Answers (2)

user648852
user648852

Reputation:

Suppose we have the same shape of a array of arrays you mention:

>>> A=np.array([np.random.random((4,3)), np.random.random((3,2))])
>>> A
array([ array([[ 0.20621572,  0.83799579,  0.11064094],
       [ 0.43473089,  0.68767982,  0.36339786],
       [ 0.91399729,  0.1408565 ,  0.76830952],
       [ 0.17096626,  0.49473758,  0.158627  ]]),
       array([[ 0.95823229,  0.75178047],
       [ 0.25873872,  0.67465796],
       [ 0.83685788,  0.21377079]])], dtype=object)

We can test each elements with a where clause:

>>> A[0]>.2
array([[ True,  True, False],
       [ True,  True,  True],
       [ True, False,  True],
       [False,  True, False]], dtype=bool)

But not the whole thing:

>>> A>.2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So just rebuild the array B thus:

>>> B=np.array([a>.2 for a in A])
>>> B
array([ array([[ True,  True, False],
       [ True,  True,  True],
       [ True, False,  True],
       [False,  True, False]], dtype=bool),
       array([[ True,  True],
       [ True,  True],
       [ True,  True]], dtype=bool)], dtype=object)

Upvotes: 2

Soronbe
Soronbe

Reputation: 926

Using List Comprehensions for 1 matrix

def compare(matrix,flo):
    return  [[x>flo for x in y] for y in matrix]

Assuming I understood your question correctly and for example

matrix= [[0,1],[2,3]]
print(compare(matrix,1.5))

should print [[False, False], [True, True]]

For a list of matrices:

def compareList(listofmatrices,flo):
    return [[[x>flo for x in y] for y in matrix] for matrix in listofmatrices]

or

def compareList(listofmatrices,flo):
    return [compare(matrix,flo) for matrix in listofmatrices]

UPDATE: recursive function:

def compareList(listofmatrices,flo):
    if(isinstance(listofmatrices, (int, float))):
        return listofmatrices > flo
    return [compareList(matrix,flo) for matrix in listofmatrices]

Upvotes: 0

Related Questions