3

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?

3
  • You want to fill it with 700 elements that are true or you want to fill 70% of array values to True Commented Nov 17, 2018 at 17:58
  • I want to fill the array with exactly 700 true values that are randomly distributed in the array of 5956 values. Hence 800 true and 5956-800 false Commented Nov 17, 2018 at 18:02
  • Generate 700 random values (without replacement) from the 5956 range, and use those to set values of a to 1. Commented Nov 17, 2018 at 18:14

2 Answers 2

4
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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

FYI: It would be bit more efficient to write arr = np.zeros(5956, dtype=bool); arr[:700] = 1 and then shuffle arr.
fair argument Warren :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.