Vectorize numpy array for loop

 ̄綄美尐妖づ 提交于 2021-02-08 04:41:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!