问题
I'm trying to figure out how to vectorize the following loop:
for i in range(1,size):
if a[i] < a[i-1]:
b[i] = a[i]
else: b[i] = b[i-1]
b is a (large) array of the same size as a. I could use
numpy.where(a[1:]<a[:-1])
to replace the if statement but how do you simultaneously replace the else statement?
回答1:
I think you want something like this:
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]
回答2:
From the docs:
numpy.where(condition[, x, y])
Return elements, either from x or y, depending on condition.
So you can simplify a loop containing:
if cond:
a[i] = b[i]
else:
a[i] = c[i]
to
a = numpy.where(cond, a, b)
However, I don't think your example can be vectorized, since each element depends on the previous one.
来源:https://stackoverflow.com/questions/13938235/vectorize-numpy-array-for-loop