简体   繁体   English

Python:将数组元素与浮点数进行比较

[英]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 . 我有一个数组A=[A0,A1] ,其中A0 is a 4x3 matrix, A1 is a 3x2 matrix I want to compare A with a float, say, 1.0, element-wise. 我想将A与浮点数(例如1.0)进行逐元素比较。 The expected return B=(A>1.0) is an array with the same size as A. How to achieve this? 预期收益B=(A>1.0)是一个与A大小相同的数组。如何实现呢?

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. 我可以将A复制到C,然后将C中的所有元素重置为1.0,然后进行比较,但是我认为python(numpy / scipy)必须具有更聪明的方式来完成此操作...谢谢。

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: 我们可以使用where子句测试每个元素:

>>> 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即可:

>>> 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)

Using List Comprehensions for 1 matrix 对1个矩阵使用列表推导

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]] 应该打印[[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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM