我试图弄清楚如何矢量化以下循环:
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 语句?
我试图弄清楚如何矢量化以下循环:
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)
但是,我认为您的示例不能向量化,因为每个元素都取决于前一个元素。