python - 用与另一个数组的零相对应的零替换元素的快速方法

标签 python numpy

假设我们有两个 numpy 数组

a = np.array([ [1, 2, 0], [2, 0, 0], [-3, -1, 0] ])
b = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])

目标是在a为0的索引处设置b的元素。也就是说,我们要得到一个数组

[ [1, 2, 0], [4, 0, 0], [7, 8, 0] ]

什么是快速实现这一目标的方法?

我想先用 $a$ 生成一个掩码,然后用这个掩码替换 b 的值。但是迷失了如何做到这一点?

最佳答案

这是数组赋值:

>>> a = np.array([[1, 2, 0], [2, 0, 0], [-3, -1, 0]])
>>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

>>> a==0  # This is a boolean mask, True where the elements of `a` are zero
array([[False, False,  True],
       [False,  True,  True],
       [False, False,  True]])

>>> b[a==0] = 0  # So this is a masked assignment statement
>>> b
array([[1, 2, 0],
       [4, 0, 0],
       [7, 8, 0]])

已记录 here .

关于python - 用与另一个数组的零相对应的零替换元素的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882973/

相关文章:

python - IPython - 摆脱矩阵打印输出中的 numpy 换行符

Python 数据帧 : Seperate rows based on custom condition?

python - 在Python中从键/值对自动生成INSERT查询

python - 如何覆盖django表单中的模型字段

python - 如何在 Flask 中实现基于角色的访问控制?

Python freeze.py生成的bin无法运行

python - 使用 python 请求和漂亮的汤进行网页抓取

python - 我如何在 Python 中实现这种相似性度量?

python - 减少计算时间和大型协方差矩阵的要求

python - 有没有更快的方法来获取 MNIST 数据集的 Local Binary Pattern?