【问题标题】:How to assign zero numbers when generate randint?生成randint时如何分配零数字?
【发布时间】:2020-11-24 21:03:06
【问题描述】:

我想生成像这样的随机数

import random
import numpy as np
a=np.random.randint(8,size=(5,126))

我想要的是当一个列表生成 0 到 7 之间的 126 个随机数时,根据需要分配 0 个计数。 例如,这段代码可能会生成 630 个随机数。 我想在 630 个随机数中有 590 个计数为零的 5 行,以及 40 个计数从 1 到 7 的行。

我该怎么做?

【问题讨论】:

  • 听起来你想要一个零膨胀的随机分布。一种方法是从伯努利分布中采样,如果你得到 0,则返回 0,如果你得到 1,则分配另一个随机分布的结果,但你没有告诉我们是哪一个。

标签: python arrays numpy random


【解决方案1】:

如果您想精确计算每个整数:对于一个包含 10 个 0、5 个 1 和 5 个 2 以及形状为 (4,5) 的玩具示例,这是一种方法。您可以根据自己的选择更改数字及其计数和形状):

#create integers in the counts you want and stack them into single 1-D array
A = np.hstack((np.zeros(10),np.ones(5),np.ones(5)*2))
#randomly shuffle them
np.random.shuffle(A)
#reshape to your desire
A = A.reshape(4,5)

样本输出:

[[2. 0. 1. 1. 2.]
 [1. 1. 0. 0. 2.]
 [1. 2. 0. 0. 0.]
 [0. 0. 0. 0. 2.]]

如果您只需要 0 的精确计数:根据 @FBruzzesi 的评论,这里有一个 10 个零、10 个 1/2 和 @987654324 形状的玩具示例的方法@。您可以根据自己的选择更改数字及其计数和形状):

#create integers in the counts you want and stack them into single 1-D array
A = np.hstack([np.zeros(10),np.random.randint(1,3,size=10)])
#randomly shuffle them
np.random.shuffle(A)
#reshape to your desire
A = A.reshape(4,5)

样本输出:

[[1. 2. 1. 2. 2.]
 [0. 0. 0. 0. 1.]
 [0. 1. 2. 0. 0.]
 [0. 0. 0. 1. 1.]]

【讨论】:

  • 为了完整性和直接解决操作问题,您可以使用A = np.hstack([np.zeros(590), np.random.randint(1, 8,size=40)]).reshape(5,126)
  • @FBruzzesi 谢谢。问题的文字有点不清楚。我假设 OP 想要每个整数的精确计数。但是,如果它只是 0 的精确计数,那么您的评论是正确的。添加它来回答:)
  • 我假设它们是 1 到 7 之间的 40 个随机整数,因为你不能将 40 除以 7:D
【解决方案2】:

我想这就是你要找的:

import numpy as np

arr = np.random.randint(1, 8, (5, 126))
idx = np.random.choice(range(arr.size), 590, replace=False)
arr[np.unravel_index(idx, arr.shape)] = 0

print (np.sum(arr == 0))

【讨论】:

    【解决方案3】:

    您无法一步完成,但您可以尝试以下步骤: 在 [0-7] 范围内生成 126 个随机整数(包括在内)。

    然后计算数组中零的数量(应该在 16 ~ 126/8 左右)。

    现在您可以将一些值(非零)随机设置为 0,直到通过遍历数组达到所需的数字。

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 2019-01-17
      • 1970-01-01
      • 2023-01-16
      • 2019-10-19
      • 2019-08-11
      • 2013-12-03
      • 2021-09-10
      • 1970-01-01
      相关资源
      最近更新 更多