使用 numpy 数组对另一个数组进行条件运算

Use numpy array to do conditional operations on another array

假设我有 2 个数组:

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

b = np.array([0, 0.5, 0.25, 0.9])

我想做的是取数组 b 中的值,并根据它的索引将其乘以数组 a 中的值。

所以数组 a 中的第一个值是 2。我希望数组 b 中那个索引位置的值乘以那个值。因此在数组 b 中,索引位置 2 的值为 0.25,因此数组 a 中的值 (2) 乘以 0.25

我知道它可以通过迭代来完成,但我正在尝试弄清楚它是如何完成元素操作的。

这是我完成的迭代方式:

result = np.array([])
for idx in a:
    result = np.append(result, (b[idx] * idx))

得到结果:

print(result)
[0.5 0.5 0.  0.  0.5 0.5 0.  0.  0.  0.  2.7 0.  0.5 0.  0.  0.5]

什么是元素等价物?

整数数组可以用作 numpy 中的索引。因此,你可以简单地做这样的事情

b[a] * a

编辑:

为了完整起见,每次调用 append 时,您的迭代解决方案都会触发新的内存分配(请参阅 this page 的 'returns' 部分)。由于您现在已经确定了输出的形状(即 a.shape),因此最好提前分配输出数组,例如result = np.empty(a.shape)然后循环往复

所以有几种方法可以做到这一点,但如果你想要纯粹的 element-wise 操作,你可以执行以下操作:

在得到结果之前,b的每个元素都通过其索引进行转换。所以创建另一个向量 n.

n = np.arange(len(b)) * b

# In the example, n now equals [0. , 0.5, 0.5, 2.7]

# then the result is just n indexed by a

result = n[a]

# result = [0.5, 0.5, 0. , 0. , 0.5, 0.5, 0. , 0. , 0. , 0. , 2.7, 0. , 0.5, 0. , 0. , 0.5]