例如:
pre_hold_list = [-2,0,0,-1,0,0,0,3,0,0]
hold_condition = lambda x:x != 0
output = np.hold(pre_hold_list, hold_condition)
[-2,-2,-2,-1,-1,-1,-1,3,3,3] #result of output
where条件是当前值不是零,该函数将保持符合此条件的值,直到符合此条件的下一个值(即,它将保持-2 -1 -1 -1,然后3)。
np.hold()或np.step()的搜索不会在Google上给我任何东西。
否则,我使用库姆和差异的累积性质编码了一个函数。如果有一种改进的方法,请告诉我。
Edit: 我在解决方案和@willem van onsem之间进行了性能检查,而我的时间则很小。
def hold_func():
start = time.time()
for i in range(1000):
x = np.random.randint(-5, 5, 1000)
hold(x, x != 0)
print(time.time() - start)
def holdtil_func():
start = time.time()
for i in range(1000):
x = np.random.randint(-5, 5, 1000)
holdtil(x, x != 0)
print(time.time() - start)
hold_func()
holdtil_func()
#0.055173397064208984
#0.045740604400634766
您可以在这里使用
cumsum(…)
和diff()
[numpy-doc]::
import numpy as np
def hold(iterable, condition):
cond = np.array(condition)
vals = np.array(iterable)
a = vals * cond
a[cond] = np.diff(np.hstack(((0,), a[cond])))
return a.cumsum()
第一个参数是包含元素的iterable
,第二个参数是与布尔值相同长度的触觉。
例如:
condition
功能如下。 FURST我们制作了两个迭代的副本(如果尚未这样,将它们转换为numpy阵列)。您可以忽略如果这些是numpy阵列。
next我们执行一个元素乘法,以使条件所做的值not
保持零。NEXT我们计算条件下的每个项目与下一个项目之间的差异,然后将其设置为
>>> a
array([-2, 0, 0, -1, 0, 0, 0, 3, 0, 0])
>>> hold(a, a != 0)
array([-2, -2, -2, -1, -1, -1, -1, 3, 3, 3])
>>> hold(a, a != 0)
array([-2, -2, -2, -1, -1, -1, -1, 3, 3, 3])
。最后,我们可以使用
a
的卡符号总和,因为a
确保这将导致正确的重复。