python - 如何在 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.
解决方案
你可以试试这个:
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)
推荐阅读
- r - 过滤任何不符合条件的变量时,filter_at 不起作用
- android - Android 改造 2 发布带有动态标头的原始 json
- c# - 如何为非管理员用户安排任务?
- python - 从 flask_sqlalchemy 导入 SQLAlchemy 找不到模块
- javascript - P5.js 流体彩虹效果
- json - 是否有用于从 DF 创建嵌套 JSON 文件的 python 函数?
- angular - 禁用时表单控件值变为空 OnSubmit
- python - 从 ModelMultipleChoiceField 复选框中检索值
- python-3.x - Pyomo ModelFactory(多个子模型的模型)使用 OOP 进行设计
- r - 编写间接引用变量以绕过硬编码的R代码效率低下吗?