在列中生成 True 和 False 的 Python 代码

发布于 2025-01-20 02:23:49 字数 311 浏览 3 评论 0原文

我分配了一项任务来创建一个列,其中包含布尔值“真/假”,表示“通过”,但有一个特定条件,即该列应具有 80% 的真值和 20% 的假值。

我尝试使用随机 True/False 值创建 Pass 列,但无法了解如何生成 8/10 true 和其余 False。

我的代码如下:

Pass=[] 
i=1 
while i<5:
    choices=random.choice([True,False])
    Pass.append(choices)
    i+=1

请帮我提供建议或代码块以供参考。谢谢

I have assigned a task to create a column saying "Pass" with boolean values - "true/false" but with a certain condition that the column should have 80% True values and 20% False.

I tried creating the column Pass with random True/False values but was unable to get how to generate 8/10 true and remaining False.

My code is below:

Pass=[] 
i=1 
while i<5:
    choices=random.choice([True,False])
    Pass.append(choices)
    i+=1

Please help me with suggestions or a block of code for reference. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

咋地 2025-01-27 02:23:49

continue

You can use random.choices and provide weights:

import random
# For a single Element
random.choices([True, False], weights=[8, 2])[0]

random.choices can return multiple samples, so it gives you a one-element list. If if you already know how many values you need (number of rows), you can also tell choices how many it should generate:

# For multiple Elements
random.choices([True, False], weights=[8, 2], k=20)
# [False, True, True, False, True, True, True, True, True, True, True, False, False, False, True, True, True, True, True, True]

According to the documentation, you can save a little work by supplying cumulated weights instead of weights:

random.choices([True, False], cum_weights=[8, 10], k=20)

tl;dr:

Pass = random.choices([True, False], weights=[8, 2], k=4)
三人与歌 2025-01-27 02:23:49

您可以使用 random.choice 设置概率()p 参数。

import numpy as np

print(np.random.choice([True,False],size=5,p=[0.8,0.2]))

输出:

[False  True False  True  True]

You can set the probablity with random.choice() with the p-parameter.

import numpy as np

print(np.random.choice([True,False],size=5,p=[0.8,0.2]))

Output:

[False  True False  True  True]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文