【问题标题】:Python: compare an array element-wise with a floatPython:将数组元素与浮点数进行比较
【发布时间】:2015-03-24 03:30:28
【问题描述】:

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

我可以将A复制到C,然后将C中的所有元素重置为1.0,然后进行比较,但我认为python(numpy/scipy)必须有更聪明的方法来做到这一点...... 谢谢。

【问题讨论】:

  • 您的 A 具有对象的 dtype,只不过是一个数组列表。 numpy 的大部分功能都在于处理多维数字数组。
  • 一些操作,比如基本的数学操作,会“通过”到内部数组。我不知道是否有一份清单,列出了哪些有效,哪些无效。

标签: python arrays numpy logical-operators


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    对 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]
    

    【讨论】:

    • 谢谢。是的,3 个 for 循环肯定会起作用。但我想知道 python/numpy 是否有一些内置功能来执行张量与标量元素的比较?我的意思是,如果以后我有一个等级为 100 的张量,例如,手工编写的代码会很麻烦(100 个 for 循环,当然不想要那个......)
    • @Void 你可以递归地做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 2021-06-24
    • 2021-05-28
    • 2017-08-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多