How to assign zero numbers when generate randint?

Viewed 182

I want to generate random numbers like

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

What I want is when a list generates 126 random numbers between 0 to 7, assign 0 count as I want. For example, maybe this code generates 630 random numbers. I want to have 5 rows with 590 count zero, and 40 count one to seven in 630 random numbers.

How could I do this?

3 Answers

If you want exact count for EVERY integer: Here is a way to do it for a toy example of 10 zeros, 5 ones and 5 twos and a shape of (4,5). You can change the numbers and their counts and shape to your choice):

#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)

Sample output:

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

If you want exact count ONLY FOR 0s: Per @FBruzzesi's comment, here is a way to do it for a toy example of 10 zeros, and 10 ones/twos and a shape of (4,5). You can change the numbers and their counts and shape to your choice):

#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)

Sample output:

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

I think this is what you are looking for:

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))

You cannot do this in one step but you can try the following procedure: Generate 126 random integers in range [0-7] (included).

Then you count the number of zeroes in the array (it should be around 16 ~ 126/8).

Now you can randomly set some values (that are not zeros) at 0 until you reach the desired number by iterating through the array.

Related