矢量化 numpy 数组以进行循环



我正在尝试弄清楚如何矢量化以下循环:

for i in range(1,size):
    if a[i] < a[i-1]:
        b[i] = a[i]
    else: b[i] = b[i-1]

b 是与 a 大小相同的(大)数组。我可以使用

numpy.where(a[1:]<a[:-1])

替换 if 语句,但如何同时替换 else 语句?

我想你想要这样的东西:

import numpy as np
def foo(a, b):
    # cond is a boolean array marking where the condition is met
    cond = a[1:] < a[:-1]
    cond = np.insert(cond, 0, False)
    # values is an array of the items in from a that will be used to fill b
    values = a[cond]
    values = np.insert(values, 0, b[0])
    # labels is an array of increasing indices into values
    label = cond.cumsum()
    b[:] = values[label]

从文档中:

numpy.where(condition[, x, y])

返回元素,从 x 或 y 返回,具体取决于条件。

因此,您可以简化包含以下内容的循环:

if cond:
    a[i] = b[i]
else:
    a[i] = c[i]

a = numpy.where(cond, a, b)

但是,我认为您的示例无法矢量化,因为每个元素都依赖于前一个元素。

最新更新