数组中的总和,直到达到给定值。

时间:2018-09-17 15:12:38

标签: python python-2.7 numpy random

我有几个带有值的numpy数组,如下所示:

po_freq1 = [0.01408451 0.05633803 0.14084507 0.02816901 0.01408451 0.01408451
0.05633803 0.05633803 0.01408451 0.01408451 0.01408451 0.01408451
0.02816901 0.07042254 0.01408451 0.01408451 0.04225352 0.11267606
0.04225352 0.01408451 0.04225352 0.02816901 0.01408451 0.04225352
0.05633803 0.01408451 0.01408451 0.01408451]
我的目标是从我的数组中随机选择一些值,并对这些值求和,直到达到给定的值(例如0.90)。有人有主意吗?

2 个答案:

答案 0 :(得分:1)

您可以使用cumsumargmin,将数组随机排列以使选择随机:

arr = np.array([0.87868619, 0.08184167, 0.01502171, 0.96840561, 0.31431041,
       0.531577  , 0.66069971, 0.1204876 , 0.9684556 , 0.81405872,
       0.48118081, 0.91681978, 0.15017044, 0.50540813, 0.11617046,
       0.01897202, 0.1894475 , 0.94660911, 0.46030856, 0.04641654])
np.random.shuffle(arr)

例如,对于阈值5

>>> (np.cumsum(arr)<=5).argmin()
11

这为您提供了应该停止求和的索引。这将比while循环更快,因为操作是矢量化的。

In [38]: np.sum(arr[:11])
Out[38]: 4.15852117

In [39]: np.sum(arr[:12])
Out[39]: 5.126976770000001

答案 1 :(得分:0)

使用随机包和while循环

import random
po_freq1 = [0.01408451, 0.05633803, 0.14084507, 0.02816901, 0.01408451, 0.01408451,
0.05633803, 0.05633803, 0.01408451, 0.01408451, 0.01408451, 0.01408451,
0.02816901, 0.07042254, 0.01408451, 0.01408451, 0.04225352, 0.11267606,
0.04225352, 0.01408451, 0.04225352, 0.02816901, 0.01408451, 0.04225352,
0.05633803, 0.01408451, 0.01408451, 0.01408451]

sumv = 0.
while sumv<0.9: sumv += random.choice(po_freq1)
print (sumv)