首页 > 解决方案 > 如何在 numpy 选择概率中重复一个值

问题描述

我想重复 0.1 五次,因为所需的概率总数等于 9。有什么建议吗?在 R 中,它可以通过使用rep函数来完成。python中有没有类似的功能?

import numpy as np
np.random.choice(np.arange(1, 4, 1/3), 3, p=[[0.1]*5, 0, 0.3, 0.2, 0])
#> TypeError: float() argument must be a string or a number, not 'list'
#> 
#> The above exception was the direct cause of the following exception:
#> 
#> Traceback (most recent call last):
#>   File "F:\miniconda_pf\envs\tensor\lib\site-packages\reprexlite\code.py", line 69, in evaluate
#>     result = eval(str(self).strip(), scope, scope)
#>   File "<string>", line 1, in <module>
#>   File "mtrand.pyx", line 918, in numpy.random.mtrand.RandomState.choice
#> ValueError: setting an array element with a sequence.

标签: pythonnumpy

解决方案


你可以试试这个:

probs = [0.1 for _ in range(5)]
probs.extend([0, 0.3, 0.2, 0])
np.random.choice(np.arange(1, 4, 1/3), 3, p=probs)

推荐阅读