【问题标题】:Updating a numpy array values based on multiple conditions根据多个条件更新 numpy 数组值
【发布时间】:2019-05-02 10:57:10
【问题描述】:

我有一个数组P,如下图:

P
array([[ 0.49530662,  0.32619367,  0.54593724, -0.0224462 ],
       [-0.10503237,  0.48607405,  0.28572714,  0.15175049],
       [ 0.0286128 , -0.32407902, -0.56598029, -0.26743756],
       [ 0.14353725, -0.35624814,  0.25655861, -0.09241335]])

还有一个向量y:

y
array([0, 0, 1, 0], dtype=int16)

我想修改另一个矩阵Z,它与P具有相同的维度,例如Z_ij = y_jZ_ij < 0时。

在上面的例子中,我的 Z 矩阵应该是

Z = array([[-, -, -, 0],
       [0, -, -, -],
       [-, 0, 1, 0],
       [-, 0, -, 0]])

其中“-”表示原始Z 值。我想到的是非常简单的实现,它基本上遍历Z 的每一行并将列值与相应的YP 进行比较。你知道更好的 pythonic/numpy 方法吗?

【问题讨论】:

  • 不会 np.where 按照您上一个问题的链接副本中的建议工作 - stackoverflow.com/questions/55947579
  • 现在已经清除了。刚刚意识到它就像 if else 一样工作。

标签: python arrays python-3.x numpy


【解决方案1】:

您需要的是np.where。这是如何使用它:-

import numpy as np
z = np.array([[ 0.49530662,  0.32619367,  0.54593724, -0.0224462 ],
       [-0.10503237,  0.48607405,  0.28572714,  0.15175049],
       [ 0.0286128 , -0.32407902, -0.56598029, -0.26743756],
       [ 0.14353725, -0.35624814,  0.25655861, -0.09241335]])
y=([0, 0, 1, 0])
result = np.where(z<0,y,z)
#Where z<0, replace it by y

结果

>>> print(result)
[[0.49530662 0.32619367 0.54593724 0.        ]
 [0.         0.48607405 0.28572714 0.15175049]
 [0.0286128  0.         1.         0.        ]
 [0.14353725 0.         0.25655861 0.        ]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多