【问题标题】:Numpy replacing elements based on logic and value in an identically shaped array [duplicate]基于相同形状数组中的逻辑和值的Numpy替换元素[重复]
【发布时间】:2019-11-14 09:38:12
【问题描述】:

我有 2 个 numpy 数组。一个用布尔值填充,另一个用数值填充。

我将如何根据布尔数组中的当前值对数值数组执行逻辑。

例如如果为真且 > 5,则将值设为假

matrix1
matrix2

newMatrix = matrix1 > 5 where matrix2 value is false

请注意,这些数组具有相同的形状,例如

[[0, 1, 1],  
[1, 0, 0]]

[[3, 1, 0]  
[6, 2, 6]]

我想要的结果是一个新的布尔矩阵,如果它的值在布尔数组中为真,并且数值数组中的等效值大于 5,例如

[[0, 0, 0]  
[1, 0, 0]]

【问题讨论】:

标签: python arrays numpy if-statement logical-operators


【解决方案1】:

最清晰的方法:

import numpy as np

matrix1 = np.array([[3, 1, 0],
                    [6, 2, 6]])

matrix2 = np.array([[0, 1, 1],
                    [1, 0, 0]])

r,c = matrix1.shape

res = np.zeros((r,c))

for i in range(r):
    for j in range(c):
        if matrix1[i,j]>5 and matrix2[i,j]==1:
            res[i,j]=1

结果

array([[0., 0., 0.],
       [1., 0., 0.]])

一种更高级的方式,使用numpy.where()

import numpy as np

matrix1 = np.array([[3, 1, 0],
                    [6, 2, 6]])

matrix2 = np.array([[0, 1, 1],
                    [1, 0, 0]])

r,c = matrix1.shape

res = np.zeros((r,c))

res[np.where((matrix1>5) & (matrix2==1))]=1

结果

array([[0., 0., 0.],
       [1., 0., 0.]])

【讨论】:

    【解决方案2】:
    newMatrix = np.logical_and(matrix2 == 0, matrix1 > 5 )
    

    这将遍历所有元素,并在来自matrix == 0matrix1 > 5 的布尔值对之间创建一个“与”。请注意,matrix1 > 5 类型的表达式会生成一个布尔值矩阵。

    如果你想要 0,1 而不是 False,True,你可以在结果中加上 +0:

    newMatrix = np.logical_and(matrix2 == 0, matrix1 > 5 ) + 0
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 2020-05-06
      • 1970-01-01
      • 2017-01-07
      • 2018-12-23
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多