我需要对numpy数组进行逻辑迭代,该值取决于其他数组的元素。我在下面编写了用于澄清问题的代码。有没有解决循环问题的建议吗?
Code
a = np.array(['a', 'b', 'a', 'a', 'b', 'a'])
b = np.array([150, 154, 147, 126, 148, 125])
c = np.zeros_like(b)
c[0] = 150
for i in range(1, c.size):
if a[i] == "b":
c[i] = c[i-1]
else:
c[i] = b[i]
这是一种使用和的组合的方法np.maximum.accumulate
,np.where
以创建要在特定时间间隔停止的步进索引,然后简单地将其索引b
将为我们提供所需的输出。
因此,一个实现将是-
mask = a!="b"
idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
out = b[idx]
逐步执行范例-
In [656]: # Inputs
...: a = np.array(['a', 'b', 'a', 'a', 'b', 'a'])
...: b = np.array([150, 154, 147, 126, 148, 125])
...:
In [657]: mask = a!="b"
In [658]: mask
Out[658]: array([ True, False, True, True, False, True], dtype=bool)
# Crux of the implmentation happens here :
In [696]: np.where(mask,np.arange(mask.size),0)
Out[696]: array([0, 0, 2, 3, 0, 5])
In [697]: np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
Out[697]: array([0, 0, 2, 3, 3, 5])# Stepped indices "intervaled" at masked places
In [698]: idx = np.maximum.accumulate(np.where(mask,np.arange(mask.size),0))
In [699]: b[idx]
Out[699]: array([150, 150, 147, 126, 126, 125])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句