Python:按元素比较数组与浮点数

Python: compare an array element-wise with a float

我有一个数组 A=[A0,A1],其中 A0 is a 4x3 matrix, A1 is a 3x2 matrix。我想将 A 与浮点数进行比较,例如 1.0,元素方面。预期的return B=(A>1.0)是一个和A大小相同的数组,如何实现呢?

我可以把A复制到C然后把C里的所有元素都重置为1.0,然后做个比较,不过我觉得python(numpy/scipy)一定有更聪明的办法来做这个... 谢谢。

对 1 个矩阵使用列表解析

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

假设我正确理解了你的问题,例如

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

应该打印 [[False, False], [True, True]]

对于矩阵列表:

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

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

更新:递归函数:

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

假设我们有你提到的相同形状的数组:

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

我们可以用 where 子句测试每个元素:

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

但不是全部:

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

所以只需重建数组 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)