Create a random array of 0 and 1 with a specific ratio

I want to generate a random array of size N that contains only 0 and 1, but I want my array to have some relationship between 0 and 1. For example, 90% of the array will be 1 and the remaining 10% will be 0 (but I want this 90% to be random throughout the array).

now i have:

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

But I can not control the ratio between 0 and 1.

+11
source share
3 answers

If you need an exact ratio of 1: 9:

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

If you need an independent 10% probability:

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

or

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

It is difficult to get the exact quantity, but you can get an approximate answer, assuming random.random returns a uniform distribution. This is strictly not true, but it is something like that. If you have a truly uniform distribution, then this is possible. You can try something like the following:

 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 

Hope this helps ...

0
source

Without using numpy, you can do the following:

 import random percent = 90 nums = percent * [1] + (100 - percent) * [0] random.shuffle(nums) 
0
source

All Articles