2

I want to create a randomized bool array with a given length a given number of True values efficiently in Python. I could not find a single command to do so, the following does what I want (twice). Is there anything more elegant way to do it?

import numpy as np

def randbool(length,numtrue):
    index_array=np.random.choice(length,numtrue,replace=False)
    bool_array=np.zeros(length,dtype=bool)
    bool_array[index_array]=True
    return(bool_array)

def randbool2(length,numtrue):
    bool_array=np.hstack((np.tile(True,numtrue),np.tile(False,length-numtrue)))
    np.random.shuffle(bool_array)
    return(bool_array)

print(randbool(5,2))
print(randbool2(5,2))
2
  • Both of these seem fine. I suspect that the first is faster Commented Nov 7, 2022 at 14:33
  • And no, I don't think that there is a more elegant approach here Commented Nov 7, 2022 at 14:37

3 Answers 3

4

Still another option:

def randbool(l,n):
   return np.random.permutation(l)<n

np.random.permutation randomly permute np.arange(l).

Sign up to request clarification or add additional context in comments.

1 Comment

Cool idea, to compare the permutations with the number of True values
1

Another suggestion:

def randbool3(length, numtrue):
    return np.random.choice(length, length, replace=False) < numtrue

Similar in efficiency to the first approach but a bit shorter in code

enter image description here

Comments

1

Both of your examples have small n and is therefore in the regime where native Python code can be faster than Numpy. For example, given:

from random import shuffle

def randbool4(length, numtrue):
    arr = [False] * length
    arr[:numtrue] = [True] * numtrue
    shuffle(arr)
    return arr

I can execute randbool4(5,2) in ~4µs. Your variants take ~30µs and mozway's are similar, while obchardon's Numpy variant takes only ~6µs which is surprisingly close.

Obviously when n gets large then Numpy's native kernels of win, but thought it worth pointing out.

Comments

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.