2

我试图弄清楚如何矢量化以下循环:

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 语句?

4

2 回答 2

2

我想你想要这样的东西:

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]
于 2012-12-18T20:37:53.453 回答
1

文档

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

根据条件从 x 或 y 返回元素。

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

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

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

但是,我认为您的示例不能向量化,因为每个元素都取决于前一个元素。

于 2012-12-18T17:30:24.273 回答