carbassot
carbassot

Reputation: 151

Initialize a np array randomly with a determined quantity of 1's and 0's

I want to initialize an array randomly with a certain quantity of 1's and 0's. The following code is all I've got. I just managed to initialize it with a random quantity of 1's and 0's, but I'd like to do it, for example (knowing that the matrix is 10x10) with 25 1's and 75 0's.

matrix = np.random.randint(2, size=(10,10))

Upvotes: 1

Views: 264

Answers (1)

nneonneo
nneonneo

Reputation: 179717

Easy: make an array of the elements you want in order, then shuffle:

# start with 100 zeroes
arr = np.zeros((100,))
# change 25 of them to 1s
arr[:25] = 1
# shuffle the array to put all the elements in random positions
np.random.shuffle(arr)
# reshape to final desired shape
arr = arr.reshape((10,10))

Upvotes: 6

Related Questions