生成具有特定比率的0和1的随机数组

时间:2014-02-05 01:04:47

标签: python random numpy

我想生成大小为N且仅包含0和1的随机数组,但我希望我的数组在0和1之间有一些比例。例如,90%的数组为1,其余10%为0(但我想要这个90%在整个阵列中是随机的。)

现在我有:

randomLabel = np.random.randint(2, size=numbers)

但我无法控制0和1之间的比例。

4 个答案:

答案 0 :(得分:25)

如果您想要1:9的精确比例:

nums = numpy.ones(1000)
nums[:100] = 0
numpy.random.shuffle(nums)

如果您想要独立的10%概率:

nums = numpy.random.choice([0, 1], size=1000, p=[.1, .9])

nums = (numpy.random.rand(1000) > 0.1).astype(int)

答案 1 :(得分:2)

您可以使用二项分布:

vector<int> q;
q.push_back(3);
q.push_back(7);
q.push_back(5);
make_heap(q.begin(), q.end());

for (auto it = q.begin(); it != q.end(); ++it) {
    cout << *it << " ";
}

答案 2 :(得分:0)

很难得到准确的计数,但假设random.random返回统一分布,您可以得到近似答案。严格来说并非如此,但只是大致如此。如果你有一个真正统一的分布,那么它是可能的。您可以尝试以下内容:

In [33]: p = random.random(10000)
In [34]: p[p <= 0.1] = 0
In [35]: p[p > 0] = 1
In [36]: sum(p == 0)
Out[36]: 997
In [37]: sum(p == 1)
Out[37]: 9003

希望这会有所帮助......

答案 3 :(得分:0)

不使用numpy,您可以执行以下操作:

import random
percent = 90

nums = percent * [1] + (100 - percent) * [0]
random.shuffle(nums)
相关问题