Oeyvind
Oeyvind

Reputation: 357

Filling a numpy array with x random values

I have a numpy array of size x, which I need to fill with 700 true.

For example:

a = np.zeros(5956)

If I want to fill this with 70 % True, I can write this:

msk = np.random.rand(len(a)) < 0.7
b = spam_df[msk]

But what if I need exactly 700 true, and the rest false?

Upvotes: 3

Views: 1592

Answers (2)

cph_sto
cph_sto

Reputation: 7585

import numpy as np
zeros = np.zeros(5956-700, dtype=bool)
ones=np.ones(700, dtype=bool)
arr=np.concatenate((ones,zeros), axis=0, out=None)
np.random.shuffle(arr)#Now, this array 'arr' is shuffled, with 700 Trues and rest False

Example - there should be 5 elements in an array with 3 True and rest False.

ones= np.ones(3, dtype=bool)   #array([True, True, True])
zeros= np.zeros(5-3, dtype=bool)   #array([False, False])
arr=np.concatenate((ones,zeros), axis=0, out=None)   #arr - array([ True,  True,  True, False, False])
np.random.shuffle(arr)    # now arr - array([False,  True,  True,  True, False])

Upvotes: 2

Filip Młynarski
Filip Młynarski

Reputation: 3612

import numpy as np

x = 5956
a = np.zeros((x), dtype=bool)

random_places = np.random.choice(x, 700, replace=False)
a[random_places] = True

Upvotes: 4

Related Questions