Iteratively Subtract Values In Array
Starting from a simple numpy array like: a = np.array([1,1,0,2,1,0]) my goal is to iteratively subtract values from this till a certain threshold. For instance, think of a includi
Solution 1:
If you want to randomly decrement a.sum()
by n
without any element of a
becoming negative, this is one way to do it:
def rnd_decrement(a, n):
c = np.cumsum(np.r_[0, a])
if n < c[-1]:
r = np.random.choice(np.arange(c[-1]) + 1, n, replace = False)
d = np.sum(r[:,None] <= c[None,:], axis=0)
return np.diff(c-d)
else:
return np.zeros_like(a)
Post a Comment for "Iteratively Subtract Values In Array"