迭代地减去数组中的值 [英] Iteratively subtract values in array
问题描述
从简单的numpy数组开始,例如:
Starting from a simple numpy array like:
a = np.array([1,1,0,2,1,0])
我的目标是从中迭代地减去值直到某个阈值.例如,考虑包含用户数量的a
.在这种情况下,向5个用户分配:
my goal is to iteratively subtract values from this till a certain threshold. For instance, think of a
including number of users. In this case 5 users are distributed with:
d = a/a.sum()
现在,我想从这个初始分布中减去4个用户,并在结果数组中始终保持值> 0.我可以构造一个随机数组减去:
Now I want to subtract 4 users at the time from this initial distribution, keeping always values > 0 in the resulting array. I can construct a random array to subtract with:
b = np.random.multinomial(4,d)
生成(一次运行)的
:
that generates (in a single run):
array([0, 1, 0, 3, 0, 0])
类似于a-b
的结果导致:
array([ 1, 0, 0, -1, 1, 0])
如何约束生成的数组在结果(a-b)
操作中永远不会产生负值?到目前为止,我认为是从另一端开始做事,生成了以下内容的随机分布:
How can I constraint that the generated array never produces a negative value in the resulting (a-b)
operation? So far I thought in doing the things from the other side, generating a random distribution of:
r = np.random.multinomial(total users - deleted users,d)
根据用户d
的初始分布,但是由于我必须在向量上应用一些指标,因此后一种方法的结果可能会有所不同.
according to the initial distribution of users d
, but since I have to apply some metrics on the vector, results might vary in the latter approach.
推荐答案
如果您想将a.sum()
随机递减n
而不使a
的任何元素变为负数,这是做到这一点的一种方法:>
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)
这篇关于迭代地减去数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!